[英]How to reverse gravity immediately?
我正在制作一个2D游戏。 我有一个立方体对象从屏幕顶部掉下来,我有立方体应该通过反转重力通过的管道。
好吧,我的物体正在从屏幕顶部掉下来。 我点击屏幕来反转重力,但它不会立即上升:改变重力方向需要时间。 当我点击屏幕时,我的物体继续下落然后上升。 当我点击屏幕时,我的动作正在形成U
形。 当它上升时也会发生同样的事情:我点击它下降,在这种情况下,我的运动形成了∩
的形状。
我想要实现的是,当我点击屏幕时,我的对象的运动有即时响应。
此外,我想要某种衰减、阻尼或平滑。
我试过这些例子没有成功:
http://docs.unity3d.com/ScriptReference/Vector2.Lerp.html
http://docs.unity3d.com/Documentation/ScriptReference/Vector3.SmoothDamp.html
这是我的代码:
public class PlayerControls : MonoBehaviour
{
public GameObject playerObject = null;
Rigidbody2D player;
public float moveSpeed;
public float up;
Vector2 targetVelocity;
void Start()
{
player = playerObject.GetComponent<Rigidbody2D>();
// Set the initial target velocity y component to the desired up velocity.
targetVelocity.y = up;
}
void Update()
{
for (int i = 0; i < Input.touchCount; i++)
{
Touch touch = Input.GetTouch(i);
if (touch.phase == TouchPhase.Ended && touch.tapCount == 1)
{
// Flip the target velocity y component.
targetVelocity.y = -targetVelocity.y;
}
}
}
void FixedUpdate()
{
// Ensure if moveSpeed changes, the target velocity does too.
targetVelocity.x = moveSpeed;
// Change the player's velocity to be closer to the target.
player.velocity = Vector2.Lerp(player.velocity, targetVelocity, 0.01f);
}
此脚本附加到下降的立方体。
当受到恒定力(在您的代码中,重力)影响时,对象将沿抛物线运动。 您正在观察抛物线: U
形。 为避免抛物线并获得即时响应( V
形),请勿使用力。 用类似的东西替换gravityScale
代码:
Vector2 velocity = player.velocity;
velocity.y = -velocity.y;
player.velocity = velocity;
这会反转速度的 y 分量,使玩家向上移动。
你还提到你想解决这个问题。 我建议添加另一个变量:目标速度。
要实现这一点,请将Vector2 targetVelocity
添加到您的组件中。 然后,在每次FixedUpdate
期间,您可以从当前速度向目标速度进行插值以逐渐改变速度。 替换当前代码中的这一行:
player.velocity = new Vector2(moveSpeed, player.velocity.y);
有了这个:
player.velocity = Vector2.Lerp(player.velocity, targetVelocity, 0.01f);
这将缓慢地将速度更改为与目标速度相同,从而平滑运动。 0.01f
是旧速度和玩家速度设置的新速度之间的位置。 选择较大的数字可以更快地进行插值,选择较小的数字可以更慢地改变方向。
然后,不要在点击屏幕时更改velocity
,而是更改targetVelocity
。 确保targetVelocity
的x
分量等于moveSpeed
,否则对象根本不会水平移动!
结合这两个更改, Start
和FixedUpdate
方法应如下所示:
void Start()
{
player = playerObject.GetComponent<Rigidbody2D>();
// Set the initial target velocity y component to the desired up velocity.
targetVelocity.y = up;
}
void Update()
{
for (int i = 0; i < Input.touchCount; i++)
{
Touch touch = Input.GetTouch(i);
if (touch.phase == TouchPhase.Ended && touch.tapCount == 1)
{
// Flip the target velocity y component.
targetVelocity.y = -targetVelocity.y;
}
}
}
void FixedUpdate()
{
// Ensure if moveSpeed changes, the target velocity does too.
targetVelocity.x = moveSpeed;
// Change the player's velocity to be closer to the target.
player.velocity = Vector2.Lerp(player.velocity, targetVelocity, 0.01f);
}
请注意,您不应在FixedUpdate
使用Input
,因为输入每帧FixedUpdate
更新,而FixedUpdate
可能每帧运行多次。 这可能会导致输入被读取两次,尤其是当帧速率变慢并且固定更新更可能需要每帧运行多次时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.