Complete C# Unity Game Developer 2D - Help

I just started my coding journey in Unity and learning C#. Everything was working fine in my course video. When I had my code below I could move using “A and D” Keys on my keyboard.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Driver : MonoBehaviour
{
   [SerializeField] float steerSpeed = 1f;
   [SerializeField] float moveSpeed = 0.01f;
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float steerAmount = Input.GetAxis("Horizontal");
        transform.Rotate(0, 0, -steerAmount);
        transform.Translate(0, moveSpeed, 0);
    }
}

But as soon as I added in * steerSpeed my capsol aka car only will go straight and I can no longer move my car around.

    // Update is called once per frame
    void Update()
    {
        float steerAmount = Input.GetAxis("Horizontal") * steerSpeed;
        transform.Rotate(0, 0, -steerAmount);
        transform.Translate(0, moveSpeed, 0);
    }

Yeah, that’s because you’re rotating and then you’re moving in a particular direction in the world (not relative to your own position).

In your second line, I think you’d be better off doing something like:
transform.position += Vector3.forward * Time.deltaTime * moveSpeed;

Oh okay, I was just following the instructor’s instructions. That’s what he said to do. But thank you for your response.

Hi BannerX,

Welcome to our community! :slight_smile:

If float steerAmount = Input.GetAxis("Horizontal"); worked, float steerAmount = Input.GetAxis("Horizontal") * steerSpeed; should have worked as well because you just changed the value of steerAmount, not the code for the movement or the rotation.

Maybe the problem is the value of steerSpeed. Log it into your console with a Debug.Log. Maybe it is 0. That would explain why the rotation suddenly stopped working. If it is 0, check the value of steerSpeed in your Inspector. The Inspector overrides the value at the top of your code because of the [SerializeField] attribute.


See also:

Thank you for the help. I had to change the speed in the inspector. I guess it didn’t like 0.001.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms