如何在Unity 3D中改变前进飞船的Y位置
How change the Y position of moving forward spaceship in Unity 3D
我已经开始了一个统一的项目3d.I想做一个向前移动的宇宙飞船,但是当我按下ArrowUp然后我想改变它的y位置到
( currentpos+ 1.5 ) 但我希望这一切顺利。
这是我的代码
transform.position += transform.forward * Time.deltaTime * 10f;
if (Input.GetKey (KeyCode.UpArrow))
transform.position = new Vector3 (transform.position.x, 5f,
transform.position.z);
通过上面的代码,对象的 Y 位置可以改变,但它工作得如此之快,我想让它平滑。
所以请帮助我。
我认为解决您的问题的最佳方法是使用 Mathf.SmoothDamp
。
示例:
private float targetY = 0f;
private float verticalVelocity = 0f;
private const float smoothTime = 1f;
private void Update()
{
transform.position += transform.forward * Time.deltaTime * 10f;
if (Input.GetKey(KeyCode.UpArrow))
{
targetY = 5f;
}
float y = Mathf.SmoothDamp(transform.position.y, targetY, ref verticalVelocity, smoothTime);
transform.position = new Vector3 (transform.position.x, y, transform.position.z);
}
此示例将在 1 秒内将 y
坐标平滑地更改为 5(您可以将 smoothTime
常数更改为不同的时间)。
基于您自己的代码,最简单的解决方法可能是这样的
//this sets the X position
transform.position += transform.forward * Time.deltaTime * 10f;
//if the button is pressed then modify Y
if (Input.GetKey (KeyCode.UpArrow))
transform.position += new Vector3 (0, 5f * Time.deltaTime * y_speed,0);
y_speed
可能是脚本中的 public float y_speed = 1.0f
,因此您可以从检查器中修改它以获得您想要的效果。
希望对您有所帮助!
假设你的宇宙飞船是刚体,你应该看看Rigidbody.AddForce
https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html
通过使用力,您可以非常轻松地在所有方向上获得平滑的运动,并在刚体参数(如质量)内调整它,而无需再次修改脚本。它是 Unity 物理模型的一部分。
如果您只想在 y 方向上移动,请输入像 (0,1,0) 这样的向量,但您也可以输入飞船游戏对象的 Transform.forward 向量。这样,它就会始终朝着它所面对的方向移动。
我已经开始了一个统一的项目3d.I想做一个向前移动的宇宙飞船,但是当我按下ArrowUp然后我想改变它的y位置到 ( currentpos+ 1.5 ) 但我希望这一切顺利。 这是我的代码
transform.position += transform.forward * Time.deltaTime * 10f;
if (Input.GetKey (KeyCode.UpArrow))
transform.position = new Vector3 (transform.position.x, 5f,
transform.position.z);
通过上面的代码,对象的 Y 位置可以改变,但它工作得如此之快,我想让它平滑。 所以请帮助我。
我认为解决您的问题的最佳方法是使用 Mathf.SmoothDamp
。
示例:
private float targetY = 0f;
private float verticalVelocity = 0f;
private const float smoothTime = 1f;
private void Update()
{
transform.position += transform.forward * Time.deltaTime * 10f;
if (Input.GetKey(KeyCode.UpArrow))
{
targetY = 5f;
}
float y = Mathf.SmoothDamp(transform.position.y, targetY, ref verticalVelocity, smoothTime);
transform.position = new Vector3 (transform.position.x, y, transform.position.z);
}
此示例将在 1 秒内将 y
坐标平滑地更改为 5(您可以将 smoothTime
常数更改为不同的时间)。
基于您自己的代码,最简单的解决方法可能是这样的
//this sets the X position
transform.position += transform.forward * Time.deltaTime * 10f;
//if the button is pressed then modify Y
if (Input.GetKey (KeyCode.UpArrow))
transform.position += new Vector3 (0, 5f * Time.deltaTime * y_speed,0);
y_speed
可能是脚本中的 public float y_speed = 1.0f
,因此您可以从检查器中修改它以获得您想要的效果。
希望对您有所帮助!
假设你的宇宙飞船是刚体,你应该看看Rigidbody.AddForce https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html
通过使用力,您可以非常轻松地在所有方向上获得平滑的运动,并在刚体参数(如质量)内调整它,而无需再次修改脚本。它是 Unity 物理模型的一部分。
如果您只想在 y 方向上移动,请输入像 (0,1,0) 这样的向量,但您也可以输入飞船游戏对象的 Transform.forward 向量。这样,它就会始终朝着它所面对的方向移动。