Today, I continued to learn Unity using the video series above. Using the two videos above, I started to learn scripting using C#, the scripting language Unity uses.
I started by creating a new script called PlayerMovement. We then attach this to the player, and begin writing our script in VS Code. We start by creating a public variable for the RigidBody component and name it rb, so we don’t have to type out the full name every time. We then add an AddForce command in the Start function. The Start function runs any code in it upon starting the program, but only runs it once. This code should look like this:
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
// Use this for initialization
void Start ()
{
AddForce(0,200,500);
}
// Update is called once per frame
void FixedUpdate ()
{
}
}
Next, we move this AddForce to the FixedUpdate function so the force is applied every frame. We then multiply the Z axis number by Time.deltaTime, which will make the force be applied the same no matter what your framerate is. the code should look like this:
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void FixedUpdate ()
{
rb.AddForce(0,0,forwardForce * Time.deltaTime);
}
}
Next, create public variable for the forward and sideways force that we will now use. we add if statements that get key inputs and adds a left force if the A key if pressed, or a right force if the D key is pressed. The code should look like this:
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
public float forwardForce = 200f;
public float sidewaysForce = 500f;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void FixedUpdate ()
{
rb.AddForce(0,0,forwardForce * Time.deltaTime);
if ( Input.GetKey("d"))
{
rb.AddForce(sidewaysForce * Time.deltaTime,0,0);
}
if ( Input.GetKey("a"))
{
rb.AddForce(-sidewaysForce * Time.deltaTime,0,0);
}
}
}
And that is the end for today.