简体   繁体   English

Unity 2D C#-对撞机不起作用

[英]Unity 2D C# - Collider not working

I am working on a 2D TopDown game in Unity 5 . 我正在Unity 5中开发 2D TopDown游戏。 The collision is not working at all. 碰撞根本不起作用。 The player and the obstacle both have a 2D Collider and they are not Trigger. 玩家和障碍物都具有2D对撞机,并且它们不是触发器。 The player has a 2D Rigidbody with Kinematic set to false , gravity scale is equal to zero . 玩家有一个2D 刚体 ,其Kinematic设置为false重力比例 等于零 Maybe the movement code has something to do with it. 也许运动代码与此有关。 The code is a bit long so I'll just show you the code for moving up: 代码有点长,所以我只向您展示上移的代码:

if (Input.GetAxis ("Up") > 0) {

    if (movingDown == false) {

        posY += speed * Time.deltaTime;
        movingUp = true;
    }
} else {

    movingUp = false;
}

/.../ /.../

transform.position = new Vector3 (posX, posY, 0);

It is always setting the value of the position as long as you are pressing the up button. 只要按下向上按钮,它始终会设置位置值。 Is there a way to fix this? 有没有办法解决这个问题?

I think that the problem is that you are setting the position directly. 我认为问题在于您是直接设置职位。 So at each frame, you are telling unity exactly were the object should be, which overrides the position that would be computed from collision. 因此,在每个帧处,您都在准确地告诉对象应该是一个统一的对象,它覆盖了从碰撞中计算出的位置。

To fix this, you need to modify your movement code to add a force to your rigidbody and leave the position untouched ( see rigidbody doc, and function AddForce ( https://docs.unity3d.com/ScriptReference/Rigidbody.html ) 要解决此问题,您需要修改运动代码,以向刚体添加力并保持不变(请参见刚体文档和功能AddForce( https://docs.unity3d.com/ScriptReference/Rigidbody.html ))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM