Transform.Forward not working?

I am still learning unity and C# and am not entirely sure how everything operates. I am trying to make a first person camera that uses a rigidbody in order for it to interact with physics. I have got the player to move along the right axis perfectly. as the camera rotates so does the character and moves relative to the right axis’s direction. I did the same thing for the forward direction and it does not appear to be working. my settings for the input manager are right, there is no errors, and it is doing the same as the right axis which is working fine. I don’t know where I am going wrong. any help is great, thanks!

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

public class RigidbodyPlayerMove : MonoBehaviour
{

    public float speed = 10;
    public Rigidbody rb;
    public Transform orientation;
    float Hinput;
    float Vinput;

    void Start()
    {
        speed = speed * 100;
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    private void Update()
    {
        movement();
    }
   
    void movement()
    {

        Hinput = Input.GetAxis("Horizontal");
        Vinput = Input.GetAxis("Vertical");

        // ignore this addforce attempt at movement.
        //rb.AddForce(orientation.transform.forward * Hinput * speed * Time.deltaTime);
        //rb.AddForce(orientation.transform.right * Vinput * speed * Time.deltaTime);

        rb.velocity = transform.forward * Vinput * speed * Time.deltaTime;
        rb.velocity = transform.right * Hinput * speed * Time.deltaTime;
    }
}

Welcome!

Your issue is that line 36 and line 37 separately set the velocity.

Unfortunately, line 36 is ignored because line 37 overwrites it before the physics system gets a chance to do anything with it!

Instead, add the two vectors together, something like:

rb.velocity = transform.forward * Vinput * speed +
       transform.right * Hinput * speed;

ALSO: you should not use deltaTime in the case of setting velocity. The reason is you set the velocity (in world units per second) and the physics system moves the object on your behalf, by as much time as it deems necessary.

Only use Time.deltaTime when you are calculating a new position yourself, which you are not doing in this case.

3 Likes

wow thank you, this really helped, you are a great person. I will take this knowledge into consideration when applying them to other practices in the future. all the best!

1 Like