热门IT资讯网

unity3d实现一个人物跟随鼠标点击地面那点就移动那点,实

发表于:2024-11-24 作者:热门IT资讯网编辑
编辑最后更新 2024年11月24日,//人物方向和判断点击事件加点击特效using UnityEngine;using System.Collections;public class playerDir : MonoBehaviour



//人物方向和判断点击事件加点击特效

using UnityEngine;
using System.Collections;

public class playerDir : MonoBehaviour {

public GameObject effect_click_prefab;
private bool isMoving=false;//鼠标是否被按下
public Vector3 targetPosition=Vector3.zero;//目标位置

private PlayerMove playerMove;

void Start()
{
targetPosition=transform.position;
playerMove=this.GetComponent<PlayerMove>();

}

void Update ()
{

if(Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//拿到鼠标按下的点
RaycastHit hitInfo;
bool isCollider=Physics.Raycast(ray,out hitInfo);//定义一个射线
if(isCollider&&hitInfo.collider.tag==Tags.ground)//判断射线是否和地面接触碰撞
{
//判断是否点击到了UI层的东西
if(UICamera.hoveredObject.tag!="Accept"&&UICamera.hoveredObject.tag!="Inventory_item_grid"&&UICamera.hoveredObject.tag!="Inventory_item")
{
isMoving=true;
ShowClickEffect(hitInfo.point);
LookAtTarget(hitInfo.point);
}

}

}

//按下鼠标左建的时候停止运动
if(Input.GetMouseButtonUp(0))
{
isMoving=false;

}

if(isMoving)
{
//得到需要移动到的目标位置
//让角色朝向目标位置
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//拿到鼠标按下的点
RaycastHit hitInfo;
bool isCollider=Physics.Raycast(ray,out hitInfo);//定义一个射线
if(isCollider&&hitInfo.collider.tag==Tags.ground)//判断射线是否和地面接触碰撞
{
//让当前对象对着射线的方向
LookAtTarget(hitInfo.point);

}

}
else
{
if(playerMove.isMoving)
{
LookAtTarget(targetPosition);

}

}

}

//实例化显示特效效果
void ShowClickEffect(Vector3 hitPoint)
{
hitPoint=new Vector3(hitPoint.x,hitPoint.y+0.1f,hitPoint.z);
GameObject.Instantiate(effect_click_prefab,hitPoint,Quaternion.identity);

}

//让角色朝向目标位置和朝向的改变
void LookAtTarget(Vector3 hitPoint)
{
targetPosition=hitPoint;
targetPosition=new Vector3(targetPosition.x,transform.position.y,targetPosition.z);//得到主角朝向位置
this.transform.LookAt(targetPosition);//让主角改变

}
}


//人物移动

using UnityEngine;
using System.Collections;

//角色状态
public enum PlayerState
{
Moving,//移动
Idle //闲着


}

public class PlayerMove : MonoBehaviour {

public float speed=4f;
public PlayerState state=PlayerState.Idle;//默认状态为Idle
private playerDir dir;
private CharacterController controller;//角色控制器
public bool isMoving=false;

void Start()
{
dir=this.GetComponent<playerDir>();
controller=this.GetComponent<CharacterController>();
}

void Update ()
{
float distance=Vector3.Distance(dir.targetPosition,transform.position);//计算目标位置到当前位置
if(distance>0.3f)
{
isMoving=true;
state=PlayerState.Moving;
controller.SimpleMove(transform.forward*speed);//角色移动

}
else
{
isMoving=false;
state=PlayerState.Idle;

}
}
}


0