将玩家移向Unity 2D中的点击点

时间:2017-05-10 10:04:35

标签: c# unity2d

我正在制作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);
        }
    }
}

}

问题在于播放器每次点击仅移动一个像素。如果点击门,我希望玩家一直移动到门口。

1 个答案:

答案 0 :(得分: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);
    }
}