第三人称控制

第三人称控制

前言

经过一段时间的Unity 3D学习,练习制作了一个简单的游戏Demo。该Demo实现了一个简单的RPG副本,英雄杀死两种怪兽游戏即获胜。
该Demo使用Unity 3D的版本为 4.6.4f1。

游戏采用第三人称视角(3rd Person Controller),但是Standard Assert中的3rd Person Controller不能满足要求。因此,自己动手实现一个第三人称角色控制。下面将从角色(英雄)控制与Camera控制两方面介绍第三人称控制的实现。

英雄控制

旋转与移动

给英雄添加Character Controller组件。通过水平和垂直虚拟轴获取玩家输入,垂直虚拟轴控制前进后退,水平虚拟轴控制旋转(此过程也带动Camera绕英雄旋转)。只有当英雄在地上时方能操作,也就是controller.isGrounded==true
旋转的关键代码

//此段代码在英雄的脚本组件中
//获取水平虚拟轴输入
float horizontal = Input.GetAxis ("Horizontal");
float rotateY = horizontal * heroRotateSpeed; //英雄自转
float cameraRotateHero = horizontal * cameraRotateSpeed;//Camera绕英雄转
controller.transform.Rotate(0, rotateY*Time.deltaTime, 0); //人物调整朝向
mainCamera.transform.RotateAround(transform.position, Vector3.up, 
                                                  cameraRotateHero * Time.deltaTime); //摄像机也旋转

移动的关键代码。首先根据输入,获得移动的本地方向向量,然后将其转为世界坐标系中的方向。

float vertical = Input.GetAxis("Vertical");
Vector3 targetDirection = new Vector3 (0.0f, 0.0f, vertical);  //本地Z方向
if (targetDirection != Vector3.zero) {
targetDirection = targetDirection.normalized;
    }
movingDirection = transform.TransformDirection (targetDirection) ;  //向量变换self -> world
//...根据不同的操作设置移动速度movingSpeed,例如走、慢跑、快跑的速度是不同的
movingDirection *= movingSpeed;
if (Input.GetButton("Jump")) {
  ...}

movingDirection.y -= gravity * Time.deltaTime;  //重力
if (movingDirection != Vector3.zero) {
    collisionFlags = controller.Move (movingDirection * Time.deltaTime ); //当没有移动时,collisionFlags为None,所
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值