c# - Rigidbody2D 在撞到对撞机时停止

标签 c# unity3d

我有一个带有 Rigidbody2D 和圆形碰撞器的播放器。玩家收集带有圆形对撞机的硬币。我左右移动播放器。当它收集硬币时,硬币会被破坏,玩家会停止,所以我必须再次触摸才能继续向左/向右移动。那么,如何在不停止玩家的情况下收集硬币呢?这是我移动刚体的代码:

void TouchMove()
{
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);
        float middle = Screen.width / 2;

        if (touch.position.x < middle && touch.phase == TouchPhase.Began)
        {
            MoveLeft();
        }

        else if (touch.position.x > middle && touch.phase == TouchPhase.Began)
        {
            MoveRight();
        }
    }
    else
    {
        SetVelocityZero();
    }
}

public void MoveLeft()
{
    rb.velocity = new Vector2(-playerSpeed, 0);
}

public void MoveRight()
{
    rb.velocity = new Vector2(playerSpeed, 0);
}

public void SetVelocityZero()
{
    rb.velocity = Vector2.zero;
}

最佳答案

您的硬币不应与任何物体碰撞,尤其是玩家。

让硬币的碰撞器被触发,然后使用 OnTriggerEnter2D 来检测它何时接触到玩家以销毁硬币而不是 OnCollisionEnter2D

enter image description here

附加到你的硬币游戏对象:

void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        Debug.Log("Player detected. Destroying this coin");
        Destroy(gameObject);
    }
}

或者附加到你的玩家游戏对象:

void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.CompareTag("Coin"))
    {
        Debug.Log("Coin detected. Destroying coin");
        Destroy(collision.gameObject);
    }
}

关于c# - Rigidbody2D 在撞到对撞机时停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48211990/

相关文章:

c# - 尝试使用 MailKit 连接到邮件服务器时出现 AuthenticationException

c# - 如何手动发送键盘扫描码?

user-interface - 在 Unity3d 中,如何将 float 窗口(例如光照贴图)添加到现有的一组选项卡(例如 : Inspector)?

c# - 开源 ASP.NET MVC CMS 的评论/比较

c# - ASP.NET 中的异步 JSON 反序列化

xcode - 使用Xcode 7,Unity 5.2.3f1,iOS 9.1基本SDK构建时出现错误

c# - Unity Engine - 通过碰撞实例化预制件

unity3d - Unity 中的 GetAxis 平滑和 Time.timeScale

ios - Xcode 6 上的估计 App Store 大小显示出巨大的大小(Unity iOS 导出)

c# - Exe 文件不是从具有数据库连接的 Windows 服务运行?