Reputation: 11
When I turn my player, my character doesn't move in the direction it's pointing. My movement script is:
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
[SerializeField] public Rigidbody rb;
[SerializeField] public Rigidbody speed;
// Update is called once per frame
void FixedUpdate()
{
// These are the keys.
if ( Input.GetKey("d") )
{
rb.AddForce(speed, 0, 0);
}
if ( Input.GetKey("a") )
{
rb.AddForce(-speed, 0, 0);
}
if ( Input.GetKey("w") )
{
rb.AddForce(0, 0, speed);
}
if ( Input.GetKey("s") )
{
rb.AddForce(0, 0, -speed);
}
}
}
My turning script for the camera and the character is:
using UnityEngine;
public class CameraScript : MonoBehaviour
{
public Transform t;
int m = 1;
// Start is called before the first frame update
void FixedUpdate()
{
if ( Input.GetKey("q"))
{
transform.Rotate(0,-m, 0 * Time.deltaTime);
}
if ( Input.GetKey("e"))
{
transform.Rotate(0,m,0 * Time.deltaTime);
}
}
}
I have no error that I can tell you, sorry for the lack of info, I just don't know what's happening in my game.
Upvotes: 1
Views: 517
Reputation: 90580
In addition to Luemus' answer
First in
public Rigidbody speed;
I assume a typo and it most probably should be a
public float speed;
Then you seem to only rotate the camera but you never rotate t
which seems to be your player object reference.
Anyway, in general whenever there is any Rigidbody
and thereby the physics engine involved you shouldn't set any hard value via the Transform
component - not even in FixedUpdate
. This might break physics, collision detection and lead to strange behavior.
Rather go through the Rigidbody
component like e.g.
public Rigidbody player;
// For the Camera which I assume be not part of the Rigidbody
// It is ok to rotate in Update
void Update()
{
if (Input.GetKey(KeyCode.Q))
{
// You most likely would rather want to multiply "m" with "Time.deltaTime"
// .. not "0"
transform.Rotate(0,-m * Time.deltaTime, 0);
}
if ( Input.GetKey(KeyCode.E))
{
// Same here
transform.Rotate(0,m * Time.deltaTime, 0);
}
}
private void FixedUpdate()
{
// Now tell the player Rigidbody to mirror the camera rotation
player.MoveRotation(transform.rotation);
}
Upvotes: 0
Reputation: 333
AddForce
method uses world space!
Try using AddRelativeForce
instead:
if ( Input.GetKey("d") )
{
rb.AddRelativeForce(speed, 0, 0);
}
...
Note that AddRelativeForce
will also take the scales into account.
Or alternatively take the rb.rotation
into account:
if ( Input.GetKey("d") )
{
rb.AddForce(rb.rotation * new Vector3(speed, 0, 0));
}
...
Upvotes: 1