如何同时在两个方向上移动一个对象而不中断?



我正在尝试做一个简单的对象移动,但当我同时使用两个箭头键时,我在释放一个键并再次按下它后会遇到问题。

的例子假设我同时按下uprow和右row。物体是这样运动的。但是,如果我释放其中一个,对象就会停止。

下面是代码。顺便说一句,我知道是什么导致了错误,但如果我删除了那部分,我不知道当我释放按钮时,我该如何停止对象。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class objectControl : MonoBehaviour
{

[SerializeField] float obecjtSpeed = 500f;
void Update()
{
movementFunction();
movementStopFunction();
}
void movementFunction()
{
if (Input.GetKeyDown(KeyCode.RightArrow))
{
GetComponent<Rigidbody2D>().velocity = new Vector2 (obecjtSpeed*Time.deltaTime,0) + GetComponent<Rigidbody2D>().velocity;    
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
GetComponent<Rigidbody2D>().velocity = new Vector2 (-obecjtSpeed*Time.deltaTime,0) + GetComponent<Rigidbody2D>().velocity;    
}
if (Input.GetKeyDown(KeyCode.UpArrow))
{
GetComponent<Rigidbody2D>().velocity = new Vector2 (0,obecjtSpeed*Time.deltaTime) + GetComponent<Rigidbody2D>().velocity;    
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
GetComponent<Rigidbody2D>().velocity = new Vector2 (0,-obecjtSpeed*Time.deltaTime) + GetComponent<Rigidbody2D>().velocity;    
}
}
void movementStopFunction()
{
if (Input.GetKeyUp(KeyCode.RightArrow))
{
GetComponent<Rigidbody2D>().velocity = new Vector2 (0, 0);    
}
if (Input.GetKeyUp(KeyCode.LeftArrow))
{
GetComponent<Rigidbody2D>().velocity = new Vector2 (0, 0);    
}
if (Input.GetKeyUp(KeyCode.UpArrow))
{
GetComponent<Rigidbody2D>().velocity = new Vector2 (0, 0);    
}
if (Input.GetKeyUp(KeyCode.DownArrow))
{
GetComponent<Rigidbody2D>().velocity = new Vector2 (0, 0);    
}
}
}

首先,在分配速度时不需要乘以deltaTime。速度是物体的速度,而不是物体在坐标系中移动的距离。因此,您应该在movementFunction中删除乘以Time.deltaTime的乘法,如下所示:

if (Input.GetKeyDown(KeyCode.RightArrow))
{
GetComponent<Rigidbody2D>().velocity = new Vector2 (obecjtSpeed,0) + GetComponent<Rigidbody2D>().velocity;    
}

重复其他方向。现在,movementStopFunction在两个轴上都将速度赋值为0,所以毫无疑问它会使物体完全停止。您希望它只撤消已解除的按钮的效果。换句话说,它应该与movementFunction相反。所以你所需要做的就是拿movementFunction把每个正电都变成负电,反之亦然。例如:

if (Input.GetKeyUp(KeyCode.RightArrow))
{
GetComponent<Rigidbody2D>().velocity = new Vector2 (-obecjtSpeed,0) + GetComponent<Rigidbody2D>().velocity;    
}

注意obecjtSpeed变成了-obecjtSpeed。对其他按钮重复此过程。

这解决了你眼前的问题,但这里还有很多需要改进的地方。我不想让你不知所措,所以我只给你留下一些观点,不做过多的阐述:

  • 既然movementFunctionmovementStopFunction如此相似,考虑将它们泛化为一个函数以避免代码重复
  • 考虑在开始时缓存刚体而不是调用GetComponent那么多
  • 即使我的建议,这段代码中断,如果有任何其他的脚本,可以改变对象的速度,如碰撞或摩擦
  • 通常,你想要加速成为你的运动脚本的一部分,而不是立即分配最大速度
  • 如果玩家同时按下两个箭头(如向上和向右,而不是向上和向下),物体的速度可能超过obecjtSpeed。有些游戏认为这是一种功能,这取决于你自己

最新更新