我花了 10 个小时在 Unity 中制作了一个简单的 2D 游戏,但我在碰撞检测方面遇到了持续存在的问题。尽管遵循了教程并检查了文档,但我的碰撞并未按预期被检测到。我尝试了各种方法,包括同时使用 OnCollisionEnter2D 和 OnTriggerEnter2D,但似乎没有任何效果。我还检查了碰撞器、Rigidbody2D 组件和图层设置,但我仍然陷入困境。
问题是,当具有 70x70 对撞机的物体完全位于 10 倍大对撞机的中间时,Unity 看不到任何东西。而且没有其他碰撞器可以与较小的碰撞器碰撞。
我实现了一个脚本,该脚本应该检测玩家对象和多个目标对象(洞)之间的碰撞。我期望当玩家与这些目标发生碰撞时调用 OnCollisionEnter2D 方法,并相应地奖励分数。然而,碰撞检测根本没有触发。我添加了调试日志来跟踪代码流,但日志表明碰撞方法永远不会被触发。
我还创建了一个带有基本形状的简单测试场景来隔离问题,但即使这样也不起作用。我花了很多时间来解决这个问题,但我不知道下一步该做什么。任何帮助将不胜感激!这是我的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class Chapter1Manager : MonoBehaviour
{
public Image crosshair; // Crosshair for aiming
public Image[] holes = new Image[10]; // Array to hold hole prefabs
public Canvas canvas; // Reference to the Canvas
public int bullets = 10; // Number of bullets available
public TextMeshProUGUI bulletsCount; // UI element to display bullet count
public Image blue; // Reference to the blue object
public int points = 0; // Player's score
public TextMeshProUGUI pointsText; // UI element to display points
public int toSend = 0; // Index to track which hole to send next
void Start()
{
// Initialize the bullet count display
bulletsCount.text = bullets.ToString();
// Find all GameObjects with the tag "hole" and store them in the holes array
GameObject[] foundHoles = GameObject.FindGameObjectsWithTag("hole");
Debug.Log("Found " + foundHoles.Length + " holes.");
// Assign found hole objects to the holes array
for (int i = 0; i < foundHoles.Length && i < holes.Length; i++)
{
holes[i] = foundHoles[i].GetComponent<Image>();
Debug.Log("Assigned hole: " + holes[i].gameObject.name);
}
}
void Update()
{
// Update the points display
pointsText.text = "Points: " + points.ToString();
// Check if there are bullets left
if (bullets > 0)
{
// Check for space key press to shoot
if (Input.GetKeyDown(KeyCode.Space))
{
// Ensure we have holes left to send
if (toSend < holes.Length) // Check if toSend is in range
{
// Set the position of the current hole to the position of the crosshair
holes[toSend].gameObject.transform.position = crosshair.transform.position;
// Increment the index for the next hole and decrement the bullet count
toSend++;
bullets--;
bulletsCount.text = bullets.ToString(); // Update the bullet count display
Debug.Log("Shot fired! Bullets left: " + bullets);
}
else
{
Debug.Log("No more holes to send.");
}
}
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
// Log the name of the colliding object
Debug.Log("Collision detected with: " + collision.gameObject.name);
// Check if the collision is with the last hole sent or the blue object
if (toSend > 0 && (collision.gameObject == holes[toSend - 1].gameObject || collision.gameObject == blue.gameObject))
{
points += 10; // Increment points for a successful hit
Debug.Log("Hit! Points: " + points);
}
}
}
您能否使用此脚本和相关的 RigidBody 2D 和 Collider 2D 共享对象的 Inspector 屏幕?
只是简单的基本想法,以防万一你错过了什么: