C#&Unity3D 角色跟随鼠标点击移动
时间:2014-03-17 18:32 来源: 我爱IT技术网 作者:山风
首先,搭建好场景:导入角色控制器、导入SmoothFollow脚本、创建好地形、创建两个预设(用来在不同时间下克隆鼠标位置)、开光(打灯);
其次,理清思路:

最后,细节修改和编写脚本:
细节:角色控制器上的脚本ThirdPersonController(控制角色移动)和ThirdPersonController(控制相机跟随)关闭或者移;
将 SmoothFollow拖给相机,调整参数。
脚本:按照上面的构思去写,代码如下
using UnityEngine;
using System.Collections;
public class MouseMove : MonoBehaviour
{
public const int ANIMATION_IDLE = 0; //动画状态
public const int ANIMATION_WALK = 1;
public const int ANIMATION_RUN = 2;
private int AnimationState; //当前动画状态
private Vector3 targetPos; //存储鼠标点击在地形上的位置
public GameObject cube; //存储预设cube
public GameObject sphere; //存储预设sphere
void Start ()
{
AnimationState = ANIMATION_IDLE; //初始化动画状态为idle
//animation.wrapMode = WrapMode.Loop; //设置动画播放模式为循环播放
}
void Update ()
{
FindMouseHitPos(); //检测鼠标碰撞并获取位置方法
MoveState(); //检测动画状态方法
}
void FindMouseHitPos()
{
Ray myRay;
RaycastHit myHit;
myRay = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Input.GetMouseButtonDown(0))
{
if(Physics.Raycast(myRay,out myHit))
{
targetPos = myHit.point;
transform.LookAt(new Vector3(targetPos.x,transform.position.y,targetPos.z));
Debug.DrawLine(myRay.GetPoint(0),targetPos,Color.red);
Event mouseHit = Event.current;
if(mouseHit.isMouse)
{
if(mouseHit.clickCount==1)
{
AnimationState = ANIMATION_WALK;
GameObject mycube = Instantiate(cube,targetPos,Quaternion.identity)as GameObject;
}
else if (mouseHit.clickCount == 2)
{
AnimationState = ANIMATION_RUN;
GameObject mysphere = Instantiate(sphere, targetPos, Quaternion.identity) as GameObject;
}
}
}
}
}
void MoveState()
{
switch(AnimationState)
{
case ANIMATION_IDLE:
//animation.CrossFade("idle",0.5f);
targetPos = transform.position;
animation.Play("idle");
print("idle");
break;
case ANIMATION_WALK:
//animation.CrossFade("walk",0.5f);
animation.Play("walk");
MoveTo(1.0f);
print("walk");
break;
case ANIMATION_RUN:
//animation.CrossFade("run",0.5f);
animation.Play("run");
MoveTo(4.0f);
print("run");
break;
}
}
void MoveTo(float XCspeed)
{
CharacterController myControl=gameObject.GetComponent();
//之所以选择1.2是因为角色的中心点与 碰撞点之间有高度差
if (Mathf.Abs(Vector3.Distance(targetPos, transform.position)) >= 1.2f) //之所以选择1.2是因为角色的中心点与
{
Vector3 moveself = transform.TransformDirection(Vector3.forward);
myControl.SimpleMove(moveself * XCspeed);
}
else
{
AnimationState = ANIMATION_IDLE;
}
}
}
总结,下次会在这个工程的基础上添加自动寻路的功能,即智慧的绕过障碍物。
本文来源 我爱IT技术网 http://www.52ij.com/jishu/4149.html 转载请保留链接。
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
