Unity变换.按预期平移更改的对象方向



我正试图通过执行以下操作来移动对象:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed;
// Update is called once per frame
void Update()
{
float horznotalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 movment = new Vector3(horznotalInput,0,verticalInput);
transform.Translate(movment * Time.deltaTime *speed);
}
}

但物体的运动发生了一些奇怪的事情。

当按下"时;a";按键,对象进入

"d";下降。

"w";向右

以及";s";向左走。

当我将其更改为以下内容时:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed;
// Update is called once per frame
void Update()
{
float horznotalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
float newHorizontalPosition = transform.position.x + horznotalInput * Time.deltaTime;
float newVerticalPosition = transform.position.z + verticalInput * Time.deltaTime;
transform.position = new Vector3(newHorizontalPosition,transform.position.y,newVerticalPosition);

}
}

它正在按预期工作。

现在,我正在遵循一个教程,我复制了和他一样的内容。但这对我不起作用。

请帮忙吗?

谢谢!

Translate默认使用本地空间

听起来你的对象(或层次中的某个父对象(旋转了90°。

如果你想要全局轴,你应该使用

transform.Translate(movment * Time.deltaTime * speed, Space.World);

或者为了简化你的第二个片段,你也可以做

transform.position += movment * Time.deltaTime * speed;

最新更新