您好我正在尝试将在3D项目上工作的代码转换为游戏对象,我点击鼠标即可在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;
}
}
}
}
}
答案 0 :(得分:1)
将Camera.main.ScreenPointToRay
替换为Camera.main.ScreenToWorldPoint
,将Physics.Raycast
替换为Physics2D.Raycast
,将RaycastHit
替换为RaycastHit2D
。确保还切换到 2D碰撞器。例如, 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;
}
}
}
}
}