unity3d之角色的移动篇 -- 俯视视角下的鼠标移动

类似DOTA游戏的移动方法, 其余没什么好说的了。

using UnityEngine;
using System.Collections;

public class gogogogo : MonoBehaviour {

    public float moveSpeed;
    public Vector3 newPosition;
    public CharacterController charactercontroller;
    
    //public AnimationClip idle;
    //public AnimationClip run;
    
    // Use this for initialization
    void Start () {
        newPosition = transform.position;
    }
    
    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButton (0)) {
            locateposition ();
        }
        MoveToPosition ();
    }

    //一个获取点击鼠标点击位置的方法
    void locateposition(){
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        
        if (Physics.Raycast (ray, out hit, 1000)) {
            if(hit.collider.tag != "Player"){
                newPosition = new Vector3(hit.point.x,hit.point.y,hit.point.z);
            }
        }
    }

    //一个开始移动并且旋转的方法
    void MoveToPosition(){    
        if(Vector3.Distance(transform.position,newPosition) > 2){
            //旋转
            Quaternion newRotation = Quaternion.LookRotation (newPosition - transform.position, Vector3.forward);
            newRotation.x = 0f;
            newRotation.z = 0f;
            transform.rotation = Quaternion.Slerp (transform.rotation, newRotation, Time.deltaTime*20);
            //移动
            charactercontroller.SimpleMove (transform.forward * moveSpeed);
            
            //animation.CrossFade(run.name);
        }
        else
        {
            //animation.CrossFade(idle.name);
        }
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。