转换光线投射从3D到2D
本文关键字:2D 3D 光线投射 转换 | 更新日期: 2023-09-27 18:18:32
嗨,我试图转换一个代码,工作在3D项目获得gameobject,我点击鼠标工作在2D,因为我现在做一个2D项目
public class SetTower : MonoBehaviour {
public int selected;
public GameObject[] towers;
public float[] prices;
public GameObject tile;
private Money moneyScript;
// Use this for initialization
void Start ()
{
moneyScript = GameObject.Find("GameLogic").GetComponent<Money>();
}
// Update is called once per frame
void Update ()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 20))
{
if(hit.transform.tag == "Tile")
{
tile = hit.transform.gameObject;
}
else
{
tile = null;
}
if (Input.GetMouseButtonDown(0) && tile != null)
{
TileTaken tileScript = tile.GetComponent<TileTaken>();
if(!tileScript.isTaken && moneyScript.money >= prices[selected])
{
moneyScript.money -= prices[selected];
Vector2 pos = new Vector2(tile.transform.position.x, tile.transform.position.y);
tileScript.tower = (GameObject)Instantiate(towers[selected], pos, Quaternion.identity);
tileScript.isTaken = true;
}
}
}
}
}
将Camera.main.ScreenPointToRay
替换为Camera.main.ScreenToWorldPoint
, Physics.Raycast
替换为Physics2D.Raycast
, RaycastHit
替换为RaycastHit2D
。确保切换到2D Colliders。例如,Box Collider应该替换为Box Collider 2D。
public class SetTower : MonoBehaviour
{
public int selected;
public GameObject[] towers;
public float[] prices;
public GameObject tile;
private Money moneyScript;
// Use this for initialization
void Start()
{
moneyScript = GameObject.Find("GameLogic").GetComponent<Money>();
}
// Update is called once per frame
void Update()
{
Vector2 ray = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(ray, Vector2.zero, 20);
if (hit)
{
if (hit.transform.tag == "Tile")
{
tile = hit.transform.gameObject;
}
else
{
tile = null;
}
if (Input.GetMouseButtonDown(0) && tile != null)
{
TileTaken tileScript = tile.GetComponent<TileTaken>();
if (!tileScript.isTaken && moneyScript.money >= prices[selected])
{
//moneyScript.money -= prices[selected];
Vector2 pos = new Vector2(tile.transform.position.x, tile.transform.position.y);
//tileScript.tower = (GameObject)Instantiate(towers[selected], pos, Quaternion.identity);
//tileScript.isTaken = true;
}
}
}
}
}