我的统一项目需要帮助.相机表现得很奇怪,我试图将我的播放器朝相机所看的方向移动
问题描述:
当我转动我的播放器时,我的角色并没有朝着它指向的方向移动.我的移动脚本是:
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.
答
AddForce
方法使用世界空间!
尝试使用 AddRelativeForce
代替:
Try using AddRelativeForce
instead:
if ( Input.GetKey("d") )
{
rb.AddRelativeForce(speed, 0, 0);
}
...
请注意,AddRelativeForce
也会将比例考虑在内.
Note that AddRelativeForce
will also take the scales into account.
或者采用 rb.rotation
考虑到:
Or alternatively take the rb.rotation
into account:
if ( Input.GetKey("d") )
{
rb.AddForce(rb.rotation * new Vector3(speed, 0, 0));
}
...