Notes I decided to write about while in class.
The inspector contains transform always and you can add components. Create a sprite and add it to your assets folder. Make sure you have folders for everything and stay organized. Selecting your sprite will open its properties in the inspector. Select the game object in the heirarchy and add component. Then find sprite renderer and add it to your game object. Right next to the sprite property in the inspector click the small circle and select your sprite. If you added a sprite with others on screen and cant see it, its probably in the back. Under additional settings, use the order in layer property to determine which sprite is in front. Right click in the assets menu and create new C# script. Make sure to name it 'sprite'Movement where 'sprite' is the name of the asset. Click on it and open it up in Visual Studio or another text editor.
The default script contains using... & public class... A class contains the functions and it contains:
void Start() { Debug.log("START"); //This prints the line when the game starts and is not a default function } // which runs on start.
void Update() { Debug.log("TICK"); //This prints a line everytime the game updates and is not a default function } // which runs every frame.
Make sure to save frequently when you edit the code. Back in Unity, add the script to the sprite that you want to move. You can drag it on or click add component and add script.
Back in Visual studio, under void update we want to transform the game object. So to refer to the transform of the sprite, we use the parameter: transform.position. The Vector refers to the x, y, z positions of the object. We add "+=" between them to increment the vector of the position. For now, in the bracket set it to 0.01f, 0f, 0f.
void Update() {
transform.position += new Vector3(0.01f, 0f, 0f);
}
Back in Unity, you can run the game by pressing the play in visual studio, we want to add a conditional to reset the position of the sprite since its is increasing every tick. So:
if (transform.position.x > 5f) { transform.position = new Vector3(-transform.position.x, 0f, 0f); }
We can also do: if (Input.GetKey(KeyCode.UpArrow)) { transform.position += new Vector3(0.01f, 0f, 0f); }
Scope refers to the function is enclosed in. Within the 'Scope' of the public class, variables can be refered to by and function within the public class. They can even be refered to by other classes. 'public' is an access modifier. If a variable or function is given a private modifier, it will not be accessable outside the class and will not show up in unity.
public bool isAlive = true; // The 'bool' refers to a boolean
public float runSpeed = 1.0f; //The 'float' refers to a float
public int ammo = 5; //The 'int' refers to integers
private string name = "Michael Lucifer";
if (Input.GetKey(KeyCode.RightArrow)) {
transform.position += new Vector3(runSpeed, 0f, 0f);
}
Referencing game objects is done using 'GameObject' as a property like bool, int, or float. 'GameObject' allows the sprite that contains the script to reference other sprites. Make sure they make sense. If the player is within the
public GameObject doorLeft;
public GameObject doorRight;
//Door Left Check
if (transform.position.x > -8f && transform.position.x < -6f)
{
doorLeft.SetActive(true);
}
else
{
doorLeft.SetActive(false);
}
//Door Right Check
if (transform.position.x > 5f && transform.position.x < 7f)
{
doorRight.SetActive(true);
}
else
{
doorRight.SetActive(false);
}
In Unity, Drag the door objects into the player script in the inspect panel. Theres a place for them thats empty. The code below is for sprite changing. (Not sure if this works with animations).
public SpriteRenderer PlayerSprite;
public Sprite = sprite1;
public Sprite = sprite2;
if (player.transform.x > 0) {
PlayerSprite.sprite = sprite1;
} else if (player.transform.x < 0) {
PlayerSprite.sprite = sprite2;
}
To build a project, open build settings, click on webgl and make sure it is loaded and selected. You can just hit build and it will make compile the game to play.
Broken up into 2 parts: 2D physics and 3D physics which don't react to each other. So if youre making a 2d game make sure you use the 2D one (It should have 2D in the title). Ex: Rigidbody 2D, Circle Collider 2D... The Rigidbody gives an object its physics. The circle collider gives an object a collider. In the Rigidbody property, the material gives the sprite some physics properties. In the example, there is friction and bounciness. We use script to refer to the physics and movement.
public class jumpButton : Monobehavior {
public Rigidbody2D Rb;
public float Force;
private void Update() {
if(Input.GetKeyDown(KeyCode.Space)) {
Rb.AddForce(new Vector2(0f, Force));
//Rb.AddForceAtPosition(new Vector2(0f, Force), transform.position + Vector3.right);
Rb.angularVelocity = Force;
//Debug.Log(Rb.velocity);
}
}
}
The script above controls the bounce or jumping with the ball. The AddForceAtPosition property of the Rb variable. The code below moves the ball left and right.
public Rigidbody2D Rb;
public float Force;
//When applying a constant force it should be done in FixedUpdate, which works like Update but for the physics engine.
private void FixedUpdate()
{
Vector2 moveVector = Vector2.zero;
if(Input.GetKey(KeyCode.LeftArrow))
{
moveVector.x = -Force;
if (Rb.velocity.x > 0) // This will immediatly change the direction of the ball
{
Rb.velocity = new Vector2(0f, Rb.velocity.y);
//You might be able to use this to do a turning animation
}
}
else if (Input.GetKey(KeyCode.RightArrow))
{
moveVector.x = Force;
}
Rb.AddForce(moveVector);
}
The "OnCollisionEnter2D(Collision2D collision){}" Function checks for collisions. In the parentheses, it refers to the Collision2D collider and the build in collision method.
public class BallCollider : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log(gameObject.name + " hit " + collision.gameObject.name);
} //Physics can be implemented here
private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log(gameObject.name + " hit " + collision.gameObject.name);
} //Physics can not be implemented with these
//Like adding Dialogue options or sounds
}
The documentation of coliders and triggers shows how the Rigidbody's properties (static, kinematic, and dynamic, work with each other. Inside the chandelier, I get the component Rigidbody and refer to the velocity property, then set it to zero.
public SpriteRenderer ChandelierSprite;
public Sprite ChandelierBroken;
private void OnCollisionEnter2D(Collision2D collision) {
if (collision.gameObject.name == "ground") {
//Destroy(gameObject); //This will destroy the gameobject
//If you want to destroy the object it touches use "Destroy(collision.gameobject)"
Debug.Log(gameObject.name + " hit " + collision.gameObject.name);
//Shows what it collides with in console
GetComponent().velocity = new Vector2(0f, 0f);
//This will set the game objects velocity to 0
//ChandelierSprite.sprite = ChandelierBroken; //This will change the sprite on collision
//GetComponent().velocity = -GetComponent().velocity; ???
}
}
In script you can refer to tags you have created like .CompareTag. So with the section of code below, we use the collision detection to reset the player to the starting posiotion when it collides with something with the "reset" tag.
private void OnTriggerEnter2D(Collider2D collision) {
if (collision.CompareTag("Reset")) {
transform.position = startPosition;
}
Using UnityEngine.SceneManagement; //This is needed to use SceneManager
private void OnTriggerEnter2D(Collider2D collision) {
if (collision.CompareTag("nextScene")) {
int sceneNumber = SceneManager.GetActive().buildIndex,
if (sceneManager == 0) {
SceneManager.LoadScene(1);
//This refers to the build index in build settings
} else {
SceneManager.LoadScene(0);
}
}
}
A prefab is a preset asset or sprite. If you make an asset and drag it into your assets folder, it will keep its settings and changes. If you double click on the prefab it will update the prefab settigns. Instantiate is a gameobject property.
public GameObject BouncyBoxPrefab;
public GameObject StickyBoxPrefab;
//AnyPrefabName
private void Update() {
if(Input.GetKeyDown(KeyCode.LeftArrow)) {
Instantiate(BouncyBoxPrefab, new Vector3(-4f, 4f, 0f), Quaternion.identity);
//This vector is where the prefab spawns
//You can also use .transform.position
//Any reference-able position
} else if {
Instantiate(StickyBoxPrefab, new vector3(4f,4f,0f), Quaternion.identity);
} //"Quaternion.identity" will keep its rotation level on spawn
}
The example below will spawn prefabs randomly unlike before where they spawned at a certain position. An array is declared by type (like int) and a name (public GameObject[] prefabArray;) Random is a class with differect functions that it can call.
public GameObject[] prefabArray; //Arrays are a list of elements
//The first position starts at 0 //THe array shares the type 'GameObject'
private void Start() {
float r = Random.value;
if (r > 0.5f) {
Debug.Log("heads")
} else {
Debug.Log("Tails")
}
}
private void Update() {
if(Input.GetKeyDown(KeyCode.LeftArrow)) {
Instantiate(prefabArray[1], new Vector3(0f, 4f, 0f), Quaternion.identity);
} else if(Input.GetKeyDown(KeyCode.RightArrow)) {
Instantiate(prefabArray[0], new Vector3(0f, 4f, 0f), Quaternion.identity;
} else if (Input.GetKeyDown(KeyCode.Space)) {
int r = Random.Range(Random.Range(0,prefabArray.length));
Debug.Log(PrefabArray[0].name);
Instantiate(PrefabArray[r], new Vector3(0f,4f, Quaternion.identity));
}
}
The following code launches a ball from a launcher. On space, it will create a new ball prefab and launch it on spawn. THe script on the ball gives the ball its velocity and a death message on collision with the tag lava.
//Launcher
public GameObject BallPrefab;
public string[] MessageArr;
public float Power;
private void Update() {
if(Input.GetKeyDown(KeyCode.Space)) {
GameObject newGameObj = Instantiate(BallPrefab, transform.position, Quaternion.identity);
Ball newBall = newGameObj.GetComponent();
newBall.Launch(transform.up * Power * Random.Range(0.75f, 1.25f), MessageArr[Random.Range(0, MessageArr.Length)]);
}
}
//Ball
public Rigidbody2D Rb;
private string myMessage = "";
public void Launch(Vector2 moveVector, string message) {
Rb.velocity = moveVector;
myMessage = message;
}
private void OnCollisionEnter2D(Collision2D collision) {
if (collision.gameObject.CompareTag("Lava")) {
Debug.Log(myMessage);
Destroy(this.gameObject);
}
}
Using TMPro;
public TMP_Text Text;
Private float ourTime - 0f;
private void Update() {
ourTime += Time.deltaTime;
Text.text = "Score: " + Score.TotalPoints
}
public float Speed;
private void Update() {
transform.position += new Vector (0f, -Speed, 0f) * Time.deltaTime;
if transform.position.y < -6) {
Score.TotalPoints += 1;
transform.position = new Vector3(Random.Range(5f,5f), 0f, 0f);
Time.timeScale = Random.Range(0.5f,3.5f);
}
}
public Transform ball;
transform.lookAt(ball);