Unity Junior Programmer Mission: Create With code Unit 1 – Start your 3D Engines

In this Unit, I programmed a car moving side-to-side on a road, trying to avoid (or hit) obstacles in the way. In addition to becoming familiar with the Unity editor and workflow, I learned how to create new C# scripts and do some simple programming. By the end of the Unit, I was able to call basic functions, then declare and tweak new variables to modify the results of those functions.

https://meta.dwdenney.com/unit1/

Project Outcome:

You will have a moving vehicle with its own C# script and a road full of objects, all of which may collide with each other using physics components.

Project Milestone:

The camera will follow the vehicle down the road through the scene, allowing the player to see where it’s going.

Project Milestone:

When the player presses the up/down arrows, the vehicle will move forward and backward. When the player presses the left/right arrows, the vehicle will turn.

C# code sample

public class PlayerController : MonoBehaviour
{
    // our custom variables
    private float speed=20.0f;
    private float turnSpeed = 45.0f;
    private float horizontalInput;
    private float verticalInput;
   

    // Update is called once per frame
    void Update()
    {
        // get horizonal input to use for turning vehicle
        horizontalInput = Input.GetAxis("Horizontal");
        // get vertical input to use for moving vehicle forward/backward
        verticalInput = Input.GetAxis("Vertical");
        // move the vehicle forward based on the users  vertical input value
        transform.Translate(Vector3.forward * Time.deltaTime * speed * verticalInput);
        //rotate the vehicle based on the users horizonal input value
        transform.Rotate(Vector3.up, Time.deltaTime * turnSpeed * horizontalInput);
    }
}

public class FollowPlayer : MonoBehaviour
{
    // variable to hold the player object which is the vehicle that the player will drive.
    public GameObject player;
    // variable to hold the camera offset to provide the best view
    private Vector3 offset = new Vector3(0.37f, 10.63f, -18.44f);

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void LateUpdate()
    {
        transform.position = player.transform.position + offset;
    }
}

An advanced mod to the code was learned later on. I changed the private variables to [SerializeField] so they will show up in the UI view without making them public.

[SerializeField] private float turnSpeed = 45.0f;

Leave a Reply