unity3d游戏开发中点击移动的基本操作方法
今天教大家在unity3d游戏开发中一个很基本实用的操作——点击地面后让物体发生移动。
在场景中新建一个Plane和一个Cube,找两张不同的贴图(方便区分Plane和Cube),并将其导入到工程后分别拖曳至Plane和Cube上,将摄像机调到合适的位置。使摄像机俯视Plane,调节好Game视图。
新建C#脚本,命名为Pathfinding1,双击脚本进行编辑,代码如下:
using UnityEngine;using System.Collections;public class Pathfinding1 : MonoBehaviour {public GameObject play;public Vector3 temPos;public bool isMoving;public Quaternion rotation;// Use this for initializationvoid Start () {play = GameObject.Find("Cube");print(play);}// Update is called once per framevoid Update () {if(Input.GetMouseButtonDown(0)){//LayerMask mask = LayerMask.NameToLayer("Ground");Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);RaycastHit hit;if (Physics.Raycast(ray, out hit, 100)){print (hit.collider.name);if(hit.collider.gameObject.name=="Plane"){Debug.Log(hit.point);temPos = new Vector3(hit.point.x, play.transform.position.y,hit.point.z);if(Vector3.Distance(play.transform.position,temPos) > 0.1){isMoving = true;}}}}if(Vector3.Distance(play.transform.position,temPos) <= 0.1){isMoving = false;}if(isMoving){turn(temPos);this.GetComponent().SimpleMove((temPos-play.transform.position).normalized*5f);}}void turn(Vector3 look){rotation = Quaternion.LookRotation (temPos-play.transform.position,Vector3.up);play.transform.rotation = Quaternion.Slerp(play.transform.rotation,rotation,Time.deltaTime*6.0f);}}
代码没分行怎么看。。
页:
[1]