ray*_*yan 0 c# unity-game-engine unity5
我的游戏场景中有一个球(球体)和一个地板。Ball.cs附着在球上以控制其在游戏中的移动(球仅在垂直方向移动)。Ball 和 floor 都附有对撞机,每当球接触地板时,理想情况下游戏应该结束。
Ball.cs脚本中的OnCollisionEnter2D方法。
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();
}
Run Code Online (Sandbox Code Playgroud)
更新功能
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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是发生的事情是每当球接触地面时,它就开始在地面上滚动。它移动几个单位+X-axis然后回滚,然后最终停止。
position.X理想情况下应该是 0(因为球只在运动,Y-axis而且是在比赛期间),但是一旦球与地板碰撞,它就会开始移动。
我是 Unity 的新手,我不知道出了什么问题。
为什么会这样?
编辑:程序员的回答确实有效,但我仍然不明白水平速度的来源(有与球相关的水平速度分量)。我需要知道为什么球在水平方向移动。
我注意到isDead当碰撞发生时你设置为 true 。如果你不想球再次然后设定速度移动到Vector2.zero;中Update ,不仅在OnCollisionEnter2D功能。仅当isDead为真时才这样做。
void Update()
{
if (isDead)
{
rb2d.velocity = Vector2.zero;
}
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是在发生碰撞时冻结约束。如果您希望球再次开始滚动,则将其解冻。
private void OnCollisionEnter2D(Collision2D collision)
{
//Zero out the ball's velocity
rb2d.velocity = Vector2.zero;
//Freeze constraints
rb2d.constraints = RigidbodyConstraints2D.FreezeAll;
// If the ball collides with something set it to dead...
isDead = true;
//...and tell the game control about it.
GameController.instance.PlayerDied();
}
Run Code Online (Sandbox Code Playgroud)
之后执行rb2d.constraints = RigidbodyConstraints2D.None;解冻。
| 归档时间: |
|
| 查看次数: |
99 次 |
| 最近记录: |