如何在C#中将2D角色(带动画)移动到鼠标点击位置?

时间:2015-05-05 09:37:47

标签: c# animation unity3d

我将开发一个名为waste collection的简单游戏。如果我点击浪费,角色需要走到某些浪费并收集它。一直是角色位于屏幕的中间位置。当我们点击在角色的左侧,动画左行走需要播放。另一方面,当我们点击角色的右侧时,动画右行走需要播放。如何在此应用程序中获取点击的位置以及如何角色动画到该点击位置

public class mousepos : MonoBehaviour {

private Animator anim;
 public float speed = 1.5f;
 private Vector3 target;

 void Start () {
 anim = GetComponent<Animator>();
     target = transform.position;
 }

 void Update () {
    if (Input.GetMouseButtonDown (0)) {
                    if (**Input.mousePosition.x <= 500**) { //move skeleton on X axis to the left
                            target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
                            target.z = transform.position.z;
                            transform.localScale = new Vector3(1, 1, 1); 
                            anim.SetInteger ("Direction", 1);

                    } else if (Input.mousePosition.x >= 500) {

                            target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
                            target.z = transform.position.z;
                            transform.localScale = new Vector3(-1, 1, 1); 
                            anim.SetInteger ("Direction", 1);
                    }

            }
     transform.position = Vector3.MoveTowards(transform.position,              target, speed * Time.deltaTime);
 }    
 }

2 个答案:

答案 0 :(得分:1)

不确定你要求的是什么,但是这样的工作会起作用吗?

if (Input.GetMouseButtonDown (0)) {
    target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
    target.z = transform.position.z;
    if(target.x > transform.position.x) transform.localScale = new Vector3(1, 1, 1); 
    else if(target.x < transform.position.x) transform.localScale = new Vector3(-1, 1, 1);
    anim.SetInteger ("Direction", 1);
 } 
 transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);

答案 1 :(得分:0)

我明白了...... :)

public class mousepos:MonoBehaviour {

    private Animator anim;
    public float speed = 1.5f;
    private Vector3 target;
    private Vector3 MousePosition;
    private Vector3 PlayerPosition;
    void Start () {
    anim = GetComponent<Animator>();


    target = transform.position;

    }
    void Update () {

            if (Input.GetMouseButtonDown (0)) {

            target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
           target.z = transform.position.x;

           Debug.Log ("traaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + target.z);
           if (target.x <= target.z) {


          transform.localScale = new Vector3 (1, 1, 1); 
         anim.SetInteger ("Direction", 1);

    }
   else if (target.x >= target.z) {

                            transform.localScale = new Vector3 (-1, 1, 1); 
                            anim.SetInteger ("Direction", 1);
                    }



            }

      transform.position = Vector3.MoveTowards (transform.position, target, speed * Time.deltaTime);

    }
    }