I’ve been doing Unity for a lil while now, and I’m trying to move my character locally, however when our lil guy here rotates, he doesn’t move where he’s rotated towards, meaning they’re not moving locally. How could I tell Unity to move the player locally?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float MovementSpeed = 1000;
public float JumpHeight = 2;
public Rigidbody rb;
public Vector3 PlayerMovement;
public float CameraSpeed = 5;
public Vector3 CamMovement;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
PlayerMovement = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
CamMovement = new Vector3(Input.GetAxis("Mouse X"), 0, 0);
transform.Rotate(0, CamMovement.x, 0, Space.Self);
}
private void FixedUpdate()
{
MovePlayer(PlayerMovement);
}
void MovePlayer(Vector3 direction)
{
rb.velocity = direction * MovementSpeed * Time.deltaTime;
}
}
Tried messing around with the transform.Rotate and the void MovePlayer(Vector3 direction) to no avail.
>Solution :
First of all in general when dealing with Rigidbody you shouldn’t do anything via the Transform component at all as this might break the Physics and Collision detection and lead to strange behavior.
And then Rigidbody.velocity is in absolute world space. So if you want to move in local space all you need to do is apply the rotation to it:
private void FixedUpdate()
{
// https://docs.unity3d.com/ScriptReference/Rigidbody.MoveRotation.html
rb.MoveRotation(rb.rotation * Quaternion.Euler(0, CamMovement.x, 0));
rb.velocity = rb.rotation * PlayerMovement * MovementSpeed;
// or also
//rb.MovePosition(rb.position + rb.rotation * PlayerMovement * MovementSpeed * Time.deltaTime);
}
Further: A velocity already is a frame-rate independent value in units per second => You should not apply Time.deltaTime here.
(And why even store CamMovement as a Vector3 when anyway only ever using a single component of it?)