2017-05-10 132 views
0

我正在製作一個2D點擊遊戲,我希望玩家移動到點擊的物體上。這是我向門口移動播放器代碼:將玩家移向Unity 2D中的點擊點

using UnityEngine; 
using System.Collections; 

public class MoveOnClick : MonoBehaviour { 
public GameObject door; 
public GameObject player; 
public float speed; 
public Vector3 target; 

void Update() { 
    if (Input.GetMouseButtonDown (0)) { 
     RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.zero); 
     if (hit.collider != null) { 
      player.transform.position = Vector3.MoveTowards(player.transform.position, target, speed * Time.deltaTime); 
     } 
    } 
} 

}

的問題是,玩家只移動每次點擊一個像素。如果門被點擊,我希望玩家一直移動到門口。

回答

0

這應該工作:

void Update() { 
    if (Input.GetMouseButtonDown (0)) { 
     RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.zero); 
    target = hit.transform.position; 
    } 

    if (hit.collider != null) { 
     player.transform.position = Vector3.MoveTowards(player.transform.position, target, speed * Time.deltaTime); 
    } 
} 
相關問題