简体   繁体   English

Unity 2D 两圆对撞机

[英]Unity 2D two Circles collider

I am new to Unity and trying to write a 2D programm where I have multiple circles on a screen and make them change direction everytime they collide with another circle or a margin.我是 Unity 的新手,正在尝试编写一个 2D 程序,其中我在屏幕上有多个圆圈,并让它们在每次与另一个圆圈或边缘碰撞时改变方向。

Here is the code I wrote for when a circle collides with a margin, in the Update method:以下是我在 Update 方法中为圆与边距碰撞时编写的代码:

transform.Translate(direction * speed * Time.deltaTime);
if (transform.position.y < GameManager.bottomLeft.y + radius && direction.y < 0)
{
    direction.y = -direction.y;
}
if(transform.position.y > GameManager.topRight.y - radius && direction.y > 0)
{
    direction.y = -direction.y;
}
if(transform.position.x < GameManager.bottomLeft.x + radius && direction.x < 0)
{
    direction.x = -direction.x;
}
if(transform.position.x > GameManager.topRight.x - radius && direction.x > 0)
{
    direction.x = -direction.x;
}

direction is defined as new Vector2(Random.value, Random.value) in Start method.方向在Start方法中定义为new Vector2(Random.value, Random.value) Now I read on the internet that if two circles meet, I can implement the behaviour in现在我在网上读到,如果两个圆圈相遇,我可以在

private void OnTriggerEnter2D(Collider2D collision)
{
    if(collision.tag == "Ball")
    {
    }  
}

How can I write the code so that two circles change directions when colliding?如何编写代码以使两个圆在碰撞时改变方向?

I'm not sure how you defined direction but this changes both objects direction upon a collision if the collider is tagged as Ball , however if you are trying to do something more like a mirrored movement you may want to change something with rotation.我不确定你是如何定义direction的,但是如果对撞机被标记为Ball ,这会在碰撞时改变两个对象的direction ,但是如果你试图做一些更像镜像运动的事情,你可能想要通过旋转来改变一些东西。

private void OnTriggerEnter2D(Collider2D collision)
{
    if(collision.tag == "Ball")
    {
        GameObject CollidedObject = collision.gameObject;
        CollidedObject.direction.x = -CollidedObject.direction.x;
        CollidedObject.direction.y = -CollidedObject.direction.y;
        this.direction.x = -this.direction.x;
        this.direction.y = -this.direction.y;
    }  
}

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

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