首页 >Unity3D频道 >【Unity3D研究院之游戏开发】 > Unity3D研究院之鼠标控制角色移动与奔跑示例(二十四)
2012
05-11

Unity3D研究院之鼠标控制角色移动与奔跑示例(二十四)

最新补充。

         一般在做鼠标选择时是从摄像机向目标点发送一条射线,然后取得射线与对象相交的点来计算3D目标点。后来在开发中发现了一个问题(射线被别的对象挡住了),就是如果主角的前面有别的游戏对象挡着。此时如果使用射线的原理,鼠标选择被档的对象,这样主角就会向被当的对象的方向行走。为了解决这个问题,我放弃使用发送射线的方法,最后通过2D的方法完美的处理了这个问题。

   如下图所示,我们先把主角的3D坐标换算成屏幕中的2D坐标,当鼠标在屏幕中点击的时候取得一个目标点的2D坐标,根据这2个坐标换算出主角的2D向量。

Unity3D研究院之鼠标控制角色移动与奔跑示例(二十四) - 雨松MOMO程序研究院 - 1

然后我们在看看代码。

//将世界坐标换算成屏幕坐标

Vector3 vpos3 = Camera.main.WorldToScreenPoint(transform.position);

Vector2 vpos2 = new Vector2 (vpos3.x,vpos3.y);

 

//取得鼠标点击的屏幕坐标

Vector2 input = new Vector2 (Input.mousePosition.x,Input.mousePosition.y);

 

//取得主角到目标点的向量

Vector2 normalied = ((vpos2 – input)).normalized;

注意normalized是格式化向量,以为vpos2 – input是计算两个向量之间的距离,格式化后才是它们的方向。格式化后向量的取值范围在 -1 到 +1 之间。

 

//我们忽略Y轴的向量,把2D向量应用在3D向量中。

Vecotr3 targetDirection = new Vector3(normalied.x,0.0f,normalied.y) ;

 

//根据照相机的角度计算真实的方向

float y = Camera.main.transform.rotation.eulerAngles.y;

targetDirection = Quaternion.Euler(0f,y – 180,0f) * targetDirection;

摄像机的角度决定着主角移动的方向,y是摄像机当前角度,180是摄像机默认的角度,摄像机在旋转的时候y是会动态改变的,所以需要 y – 180 。用Quaternion.Euler()方法计算一个rotation ,然后乘以默认的向量targetDirection就是主角在3D中真实需要移动的方向。

 

//最后使用角色控制器移动主角就可以

Vector3 movement = targetDirection * moveSpeed + new Vector3 (0, verticalSpeed, 0) + inAirVelocity;

CharacterController controller = GetComponent<CharacterController>();

collisionFlags = controller.Move(movement);

 

不知道大家理解了没有?如果没有理解就在我的博客下面留言,我回即时的解答的、OK继续忙碌拉。

 

详细代码示例请看这篇文章. Unity3D研究院之处理摄像机跟随避免相机穿墙拉近的方法(四十四)

 

———————————————————–华丽的分割线—————————————-

 

       看到这个标题我相信大家应该并不陌生,一般在PC网络游戏中玩家通过鼠标左键在游戏世界中选择角色目标移动位置,接着主角将面朝点击的那个方向移动。首先就本文来说我们应当掌握的知识点是“鼠标拣选”。这是什么概念呢?其实很简单,就是玩家通过鼠标在Game视图中选择了一个点,需要得到该点在3D世界中的三维坐标系。Game视图是一个2D的平面,所以鼠标拣选的难点就是如何把一个2D坐标换算成3D坐标。我们可以使用射线的原理很好的解决这个问题,在平面中选择一个点后从摄像机向该点发射一条射线。判断:选择的这个点是否为地面,如果是地面拿到这个点的3D坐标即可。如下图所示,在场景视图中我们简单的制作了带坡度的地形,目标是用户点击带坡度或不带坡度的地形都可以顺利的到达目的地。

 

Unity3D研究院之鼠标控制角色移动与奔跑示例(二十四) - 雨松MOMO程序研究院 - 2

         
         本文依然使用角色控制器组件,不知道这个组件的朋友请看MOMO之前的文章。因为官方提供的脚本是JavaScript语言。MOMO比较喜欢C#所以放弃了在它的基础上修改,而针对本文的知识点重写编写脚本,这样也方便大家学习,毕竟官方提供的代码功能比较多,代码量也比较多。废话不多说了进入正题,首先在将模型资源载入工程,这里没有使用官方提供的包,而直接将模型资源拖拽入工程。如下图所示,直接将角色控制器包中的模型资源拖拽如层次视图当中。
Unity3D研究院之鼠标控制角色移动与奔跑示例(二十四) - 雨松MOMO程序研究院 - 3

在Project视图中鼠标右键选择Import  Package ->Script引入官方提供的脚本,这些脚本主要是应用于摄像机朝向的部分。首先在Hierarchy视图中选择摄像机组件,接着在导航栏菜单中选择Compont -> Camera-Control ->SmoothFollow脚本。实际意义是将跟随脚本绑定在摄像机之上,目的是主角移动后摄像机也能跟随主角一并移动。如下图所示,脚本绑定完毕后可在右侧监测面板视图中看到Smooth Follow脚本。Target 就是射向摄像机朝向的参照物,这里把主角对象挂了上去意思是摄像机永远跟随主角移动。
Unity3D研究院之鼠标控制角色移动与奔跑示例(二十四) - 雨松MOMO程序研究院 - 4
         
         由于官方提供的脚本并不是特别的好,摄像机永远照射在主角的后面,以至于控制主角向后回头时也无法看到主角的面部表情,所以MOMO简单的修改一下这条脚本,请注意一下我修改的地方即可。

 

SmootFollow.js
// The target we are following
var target : Transform;
// The distance in the x-z plane to the target
var distance = 10.0;
// the height we want the camera to be above the target
var height = 5.0;
// How much we
var heightDamping = 2.0;
var rotationDamping = 3.0;

// Place the script in the Camera-Control group in the component menu
@script AddComponentMenu("Camera-Control/Smooth Follow")

function LateUpdate () {
	// Early out if we don't have a target
	if (!target)
		return;

	// Calculate the current rotation angles
	var wantedRotationAngle = target.eulerAngles.y;
	var wantedHeight = target.position.y + height;

	var currentRotationAngle = transform.eulerAngles.y;
	var currentHeight = transform.position.y;

	// Damp the rotation around the y-axis
	currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);

	// Damp the height
	currentHeight = Mathf.Lerp (currentHeight, wantedHeight, heightDamping * Time.deltaTime);

	// Convert the angle into a rotation

	//下面是原始代码。
	//var currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);

	//这里是我修改的,直接让它等于1,
	//摄像机就不会旋转。
	var currentRotation = 1;

	// Set the position of the camera on the x-z plane to:
	// distance meters behind the target
	transform.position = target.position;
	transform.position -= currentRotation * Vector3.forward * distance;

	// Set the height of the camera
	transform.position.y = currentHeight;

	// Always look at the target
	transform.LookAt (target);
}

 

           
          OK ! 下面我们给主角模型添加角色控制器组件,请先把自带的控制摄像机与镜头的控制脚本删除。如下图所示主角对象身上挂着Character Controller(角色控制器组件)即可,Controller是我们自己写的脚本,用来控制主角移动。

 

Unity3D研究院之鼠标控制角色移动与奔跑示例(二十四) - 雨松MOMO程序研究院 - 5
  
        下面看一下Controller.cs完整的脚本,脚本中我们将主角共分成三个状态:站立状态、行走状态、奔跑状态。默认情况下主角处于站立状态,当鼠标选择一个目标时,主角将进入行走状态面朝目标方向行走。当连续按下鼠标左键时主角将进入奔跑状态朝向目标方向奔跑。

 

using UnityEngine;
using System.Collections;

public class Controller : MonoBehaviour
{

	//人物的三个状态 站立、行走、奔跑
	private const int HERO_IDLE = 0;
	private const int HERO_WALK = 1;
	private const int HERO_RUN = 2;

	//记录当前人物的状态
	private int gameState = 0;

	//记录鼠标点击的3D坐标点
	private Vector3 point;
	private float time;

	void Start ()
	{
		//初始设置人物为站立状态
		SetGameState(HERO_IDLE);

	}

	void Update ()
	{
		//按下鼠标左键后
		if(Input.GetMouseButtonDown(0))
		{
			//从摄像机的原点向鼠标点击的对象身上设法一条射线
			Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			RaycastHit hit;
			//当射线彭转到对象时
			if (Physics.Raycast(ray, out hit))
			{
				//目前场景中只有地形
				//其实应当在判断一下当前射线碰撞到的对象是否为地形。

				//得到在3D世界中点击的坐标
				point = hit.point;

				//设置主角面朝这个点,主角的X 与 Z轴不应当发生旋转,
				//注解1
				transform.LookAt(new Vector3(point.x,transform.position.y,point.z));

				//用户是否连续点击按钮
				if(Time.realtimeSinceStartup - time <=0.2f)
				{
						//连续点击 进入奔跑状态
						SetGameState(HERO_RUN);
				}else
				{
						//点击一次只进入走路状态
						SetGameState(HERO_WALK);
				}

				//记录本地点击鼠标的时间
				time = Time.realtimeSinceStartup;
			}
		}
	}

	void FixedUpdate()
	{

		switch(gameState)
		{
		case HERO_IDLE:

			break;
		case HERO_WALK:
			//移动主角 一次移动长度为0.05
			Move(0.05f);
			break;

		case HERO_RUN:
			//奔跑时移动的长度为0.1
			Move(0.1f);
			break;
		}

	}

	void SetGameState(int  state)
	{
		switch(state)
		{
		case HERO_IDLE:
		 	//播放站立动画
			point = transform.position;
			animation.Play("idle");
			break;
		case HERO_WALK:
			//播放行走动画
			animation.Play("walk");
			break;
		case HERO_RUN:
			//播放奔跑动画
			animation.Play("run");
			break;
		}
		gameState = state;
	}

	void Move(float speed)
	{

		//注解2
		//主角没到达目标点时,一直向该点移动
		if(Mathf.Abs(Vector3.Distance(point, transform.position))>=1.3f)
		{
			//得到角色控制器组件
			CharacterController controller  = GetComponent<CharacterController>();
			//注解3 限制移动
			Vector3 v = Vector3.ClampMagnitude(point -  transform.position,speed);
			//可以理解为主角行走或奔跑了一步
			controller.Move(v);
		}else
		{
			//到达目标时 继续保持站立状态。
			SetGameState(HERO_IDLE);
		}
	}

}

 
注解1:transform.LookAt()这个方法是设定主角对象的面朝方向,这里设定的方向是鼠标选择的目标点在游戏世界中点中的3D坐标。为了避免主角X与Z轴发生旋转(特殊情况)所以我们设定朝向的Y轴永远是主角自身的Y轴。

注解2:在这里判断主角当前位置是否到达目标位置,然后取得两点坐标差的绝对值。未到达目的继续向前行走或奔跑,达到目的主角进入站立状态等待下一次移动。
注解3:在选中目标点后主角并不是直接移动过去,应当是经过一段行走或奔跑的时间才移动过去。所以我们需要得知主角行走或奔跑下一步的坐标,那么通过Vertor3.ClampMagnitude()方法即可取得。参数1为两个坐标点之间的距离差,参数2表示行走或奔跑一步的距离,最后通过角色控制器组件提供的Move方法来移动主角。

 

Unity3D研究院之鼠标控制角色移动与奔跑示例(二十四) - 雨松MOMO程序研究院 - 6
MOMO祝大家学习愉快哇咔咔!如上图所示,MOMO双击鼠标在3D中选择了一个目标点,主角正在努力的向该点奔跑。
工程的下载地址如下:http://vdisk.weibo.com/s/abU_3
最后编辑:
作者:雨松MOMO
专注移动互联网,Unity3D游戏开发
捐 赠写博客不易,如果您想请我喝一杯星巴克的话?就进来看吧!

Unity3D研究院之鼠标控制角色移动与奔跑示例(二十四)》有 62 条评论

  1. ot1993说:

    MOMO老师,如果用C#的话,请问这段代码有什么问题呢?using UnityEngine;using System.Collections;public class cameraTarget : MonoBehaviour {public Transform target;public float height=10.0f;public float distance=5.0f;public float heightDamping=2.0f;public float rotationDamping=3.0f;// Use this for initializationvoid Start () {}// Update is called once per framevoid LateUpdate () {if(!target){return;}float wantedRotationAngle=target.eulerAngles.y;float wantedHeight=target.position.y height;float currentRotationAngle=target.eulerAngles.y;float currentHeight=transform.position.y;currentRotationAngle=Mathf.LerpAngle(currentRotationAngle,wantedRotationAngle,rotationDamping*Time.deltaTime);currentHeight=Mathf.Lerp(currentHeight,wantedHeight,heightDamping*Time.deltaTime);float currentRotation=1;transform.position=target.position;transform.position-=currentRotation*Vector3.forward*Time.deltaTime;transform.position.y=currentHeight;transform.LookAt(target);}}

  2. ot1993说:

    MOMO老师,如果用C#的话,请问这段代码有什么问题呢?using UnityEngine;using System.Collections;public class cameraTarget : MonoBehaviour { public Transform target; public float height=10.0f; public float distance=5.0f; public float heightDamping=2.0f; public float rotationDamping=3.0f; // Use this for initialization void Start () { } // Update is called once per frame void LateUpdate () { if(!target){ return; } float wantedRotationAngle=target.eulerAngles.y; float wantedHeight=target.position.y+height; float currentRotationAngle=target.eulerAngles.y; float currentHeight=transform.position.y; currentRotationAngle=Mathf.LerpAngle(currentRotationAngle,wantedRotationAngle,rotationDamping*Time.deltaTime); currentHeight=Mathf.Lerp(currentHeight,wantedHeight,heightDamping*Time.deltaTime); float currentRotation=1; transform.position=target.position; transform.position-=currentRotation*Vector3.forward*Time.deltaTime; transform.position.y=currentHeight; transform.LookAt(target); }}

  3. 一条大侠说:

    确实解压不了,Unity直接挂了。。。3.5.6和4.0的都试过了。。。。

  4. http://vdisk.weibo.com/s/abU_3 momo这里下载的package无论是win下面还是mac下面都无法解压, 好像出问题了, 有空能不能重新传一个呢~~~

  5. 宇宙说:

    controller.cs出現了以下的錯誤, 請幫忙阿MOMO老師,感謝!Assets/Standard Assets/Character Controllers/Sources/Scripts/controller.cs(45,37): error CS1525: Unexpected symbol `else’Assets/Standard Assets/Character Controllers/Sources/Scripts/controller.cs(56,14): error CS0116: A namespace can only contain types and namespace declarationsAssets/Standard Assets/Character Controllers/Sources/Scripts/controller.cs(77,14): error CS0116: A namespace can only contain types and namespace declarationsAssets/Standard Assets/Character Controllers/Sources/Scripts/controller.cs(104,21): error CS1525: Unexpected symbol `else’Assets/Standard Assets/Character Controllers/Sources/Scripts/controller.cs(107,32): error CS8025: Parsing error

  6. 旧的射线法没有问题。对新的方法,不太理解怎么用。targetDirection = Quaternion.Euler(0f,y – 180.0f, 0f) * targetDirection;到这里,targetDrection是否是角色最终要移动的向量?还是仅仅是移动的方向?后面的调用Move方法,更是不理解:ector3 movement = targetDirection * moveSpeed new Vector3(0, verticalSpeed, 0) inAirVelocity;其中verticalSpeed和inAirVelocity应该怎么设置?不跳的话是否都可以不加这两部分的向量?最后,如何判断走到了目标地点?这个是让我最不理解的,因为没有记录目标点,所以不知道如何判断结束移动。。。求详解啊

  7. 旧的射线法没有问题。对新的方法,不太理解怎么用。targetDirection = Quaternion.Euler(0f,y – 180.0f, 0f) * targetDirection;到这里,targetDrection是否是角色最终要移动的向量?还是仅仅是移动的方向?后面的调用Move方法,更是不理解:ector3 movement = targetDirection * moveSpeed + new Vector3(0, verticalSpeed, 0) + inAirVelocity;其中verticalSpeed和inAirVelocity应该怎么设置?不跳的话是否都可以不加这两部分的向量?最后,如何判断走到了目标地点?这个是让我最不理解的,因为没有记录目标点,所以不知道如何判断结束移动。。。求详解啊

  8. 在导出一下。。。BUG吧

  9. gHost 1.0说:

    雨松老师,请问怎样才能让角色在起伏地形上行走呢,按您的步骤做了之后,移动都是直线的,能让他有重力,正常点多动吗?

  10. 阿嚏说:

    雨松老师,请问,我按照你的步骤做了之后,一直出现 error CS0165: Use of unassigned local variable `hit’ 的错误,是怎么回事呢?

  11. bswbmb说:

    MOMO 老师。。不太理解Mathf.Abs(Vector3.Distance(point, transform.position))>=1.3f 这里是不是应该<=1.3f? Vector3.ClampMagnitude 不太理解这个函数的含义。。看手册。返回向量的长度,最大不超过maxLength所指示的长度。 ? 不太理解。

  12. 小黑说:

    Vector3 v = Vector3.ClampMagnitude(point – transform.position,speed); v这个返回的为什么是(0.0,0.0,0.0)?那controller.Move(v);不就没移动吗?但是却可以!我换了一个模型自己做的角色动画,走,跑,但是使用Controller脚本,模型只是原地走,原地跑?

  13. ACC说:

    Unity3D_24.unitypackage 工程导入报错Error while importing package: Couldn’t decompress package路径没有中文啊

  14. rain说:

    請問要是想在Unity Android上寫一個用按鈕來控制人物移動跳躍 要怎麼寫我寫了一個跳躍 可是我不知道要怎麼讓他跳下來地上 請問要怎麼寫if (Input.GetMouseButton(0)){ if (butJump.HitTest(Input.mousePosition)) { controller.Move((Vector3.up) * jumpSpeed); }}

  15. 小i说:

    請問…我在家自己做一個這樣的,可是我如果一直點他的頭或是點高一點的建築物,他會升天不會掉下來地面,我用了rigidbody也沒用

  16. redocx说:

    MOMO大,Physics.Raycast(ray, out hit)中的关键字out是什么意思

  17. 益达酸奶说:

    支持老乡

  18. 可可西里说:

    momo加油

  19. 鱼鱼说:

    文章不错,楼主辛苦了~~

    • 橘子大大说:

      雨大你好 我现在遇到一个问题 就是使用角色控制组件时 controller.move() 即使在平面 角色X轴也会产生轻微的倾斜 使得挂在角色上的物体也随之倾斜 这点是不必要的 请问如何解决

留下一个回复

你的email不会被公开。 必填项已用 * 标注。