【发布时间】:2019-02-03 13:53:18
【问题描述】:
我现在大部分时间都在尝试使用光线投射来移除 2D 对象。我知道如何使用 OnMouseDown 方法有效地做同样的事情,到目前为止我一直在使用它。但是我读到使用 raycastign 比使用 OnMOuseDown 方法更有效,因为 OnMouseDOwn 方法是专门为鼠标点击而设计的。查看教程以及阅读论坛,我看到人们使用 Unity 库中提供的不同光线投射技术、类和方法,但这些主要用于 3D 对象。因为我正在设计一个 2D 游戏,所以我想了解如何为 2D 对象做这件事。我已经尝试了几件事以使其正常工作,但似乎没有任何工作:
我尝试过使用 Raycasthit2D、Raycast2D,但似乎没有任何效果
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TouchTest : MonoBehaviour
{
void Start()
{
}
//public Vector2 direction;
void Update()
{
//Cast a ray in the direction specified in the inspector.
RaycastHit2D hit =
Physics2D.Raycast(this.gameObject.transform.position,
Input.GetTouch(0).position);
//If something was hit.
if (hit.collider != null)
{
//Display the point in world space where the ray hit the collider's surface.
Debug.Log("We Hit something");
}
}
}
结果应该是,当我在 Unity Remote 上触摸对象时,它会在控制台上输出“we hit something”,但它什么也没做,只是说我的 Input.GetTouch(0).position 索引超出了弹跳。尽管它经常这么说,但对于其他代码,它仍然设法执行我想要的,但是对于这个代码,它不起作用并且仍然说索引没有反弹。
【问题讨论】:
-
无论是否有输入,您都在每个
Update中进行光线投射。我建议改变它。如果您的对象有碰撞器,这应该可以工作。
标签: c# unity3d 2d game-engine raycasting