Home > database >  How do I rotate the Character to the Camera's rotation?
How do I rotate the Character to the Camera's rotation?

Time:10-29

I tried to make my character to change it's rotation to the Camera's rotation, so if my camera looking at a different direction it should make my Character move at that direction to change my Character's direction to it then my Character moves to that direction when I click "W". How can I fix it? (The Character should be the same rotation as the Camera so it can move at that direction.)

My Character Movement Script :

public Rigidbody rb;

public float moveSpeed;

public Transform Cam;

public Transform target;

void Start()
{
    
}


void Update()
{
    target.rotation = Cam.rotation;

    if (Input.GetKey(KeyCode.W))
    {
        rb.velocity = Vector3.forward * moveSpeed;
    }

    if (Input.GetKey(KeyCode.S))
    {
        rb.velocity = Vector3.back * moveSpeed;
    }

    if (Input.GetKeyDown(KeyCode.Space))
    {
        rb.velocity = Vector3.up * moveSpeed;
    }

    if (Input.GetKey(KeyCode.A))
    {
        rb.velocity = Vector3.left * moveSpeed;
    }

    if (Input.GetKey(KeyCode.D))
    {
        rb.velocity = Vector3.right * moveSpeed;
    }

    if(Input.GetKey(KeyCode.LeftShift))
    {
        moveSpeed = 8f;
    }

    if(Input.GetKey(KeyCode.LeftControl))
    {
        moveSpeed = 3f;
    }
}

}

My Camera Follow Script :

public float rotateSpeed;

private float moveX;

public Transform target;

public Vector3 offset;

private float moveY;

public Transform Cam;

void Start()
{
    
}


void Update()
{
    transform.position = target.position   offset;

    moveX = Input.GetAxis("Mouse X");

    moveY = Input.GetAxis("Mouse Y");

    transform.Rotate(0f, moveX * rotateSpeed * Time.deltaTime, 0f);

    target.rotation = Cam.rotation;
}

}

CodePudding user response:

Currently you're setting the rigidbody velocity using Vector3 properties, which will return a vector relative to the world coordinates. You'll want to set the velocity relative to the characters rotation, which you can do by changing

rb.velocity = Vector3.forward * moveSpeed;

in your character movement to

rb.velocity = target.transform.forward * moveSpeed;

etc.

  • Related