我的游戏场景中有一个球(球体)和一个地板 . Ball.cs
附着在球上以控制其在比赛中的移动(球只在垂直方向上移动) . 球和地板上都有碰撞器,只要球接触到地板,游戏就应该完美结束 .
OnCollisionEnter2D Ball.cs
脚本中的方法 .
private void OnCollisionEnter2D(Collision2D collision)
{
// Zero out the ball's velocity
rb2d.velocity = Vector2.zero;
// If the ball collides with something set it to dead...
isDead = true;
//...and tell the game control about it.
GameController.instance.PlayerDied();
}
Update 功能
void Update () {
//Don't allow control if the bird has died.
if (isDead == false)
{
//Look for input to trigger a "flap".
if (Input.GetMouseButtonDown(0))
{
//...zero out the birds current y velocity before...
rb2d.velocity = Vector2.zero;
// new Vector2(rb2d.velocity.x, 0);
//..giving the bird some upward force.
rb2d.AddForce(new Vector2(0, upForce));
}
}
}
但正在发生的事情是,每当球接触地面时,它就会开始在地面上滚动 . 它在 +X-axis
上移动了几个单位然后回滚然后最终停止 .
position.X
理想情况下应为0(因为球只在 Y-axis
中移动并且在比赛期间)但是一旦球与地板碰撞它就开始移动 .
我是Unity的新手,我不知道出了什么问题 .
为什么会这样?
EDIT :程序员's answer does work but I still don't了解水平速度来自何处(存在与球相关的水平速度分量) . 我需要知道为什么球在水平方向上移动 .
1 回答
我发现碰撞发生时你将
isDead
设置为true . 如果您不希望球再次移动,则在OnCollisionEnter2D
函数的Update
not only 中将速度设置为Vector2.zero;
. 仅当isDead
为真时才执行此操作 .另一种选择是在碰撞发生时冻结约束 . 如果你想让球再次开始滚动,那么解冻它 .
执行
rb2d.constraints = RigidbodyConstraints2D.None;
以解冻后解冻 .