首页 > 解决方案 > col.gameObject.CompareTag 不工作!当我与带有“敌人”标签的游戏​​对象发生碰撞时,不会弹出调试消息

问题描述

我的碰撞检测不起作用!当我与带有“敌人”标签的游戏​​对象发生碰撞时,不会弹出调试消息。有谁知道问题是什么?请帮忙

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//using UnityEngine.TextMeshPro;
using TMPro;
public class PlayerController : MonoBehaviour
{
    public float speed = 3;
    public float jumpPower = 1.5f;

    private Rigidbody2D rigidBody;


    // Start is called before the first frame update
    void Start()
    {
        rigidBody = GetComponent<Rigidbody2D> ();
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKey(KeyCode.A))
            transform.Translate(-.1f, 0.0f, 0.0f);
        if(Input.GetKey(KeyCode.D))
            transform.Translate(.1f, 0.0f, 0.0f);

    }
    **void OnCollisionEnter(Collision col){
    if(col.gameObject.CompareTag("Enemy")){
    Debug.Log("CONTACT");**
    }
    }
}

标签: unity3d2dcollisioncol

解决方案


不确定这是否已经解决了您的问题,但是:

该问题可能是由于您使用组件移动带有Rigidbody2D组件的对象引起的transform。这打破了物理和碰撞可能不会被调用。

而是总是通过Rigidbody2D组件并Rigidbody2D.MovePositionFixedUpdatelike中使用

bool keyA;
bool keyD;

void Update()
{
    if(Input.GetKey(KeyCode.A)) keyA = true;
    else if(Input.GetKey(KeyCode.D)) keyD = true;
}

private void FixedUpdate ()
{
    if(keyA)
    {
        keyA = false;
        rigodBody.MovePosition(rigiBody.position - Vector3.right * 0.1f);
    }
    else if(keyD)
    {
        keyD = false;
        rigidBody.MovePosition(rigidBody.position + Vector2.right * 0.1f);
    }
}

一般来说,你的刚体应该是isKinematic为了工作

注意:MovePosition 旨在与运动学刚体一起使用。


推荐阅读