Unity 基于Character Controller 组件实现简单的场景漫游

实现

获取鼠标移动输入值控制视角旋转。

deltaMouse.x = Input.GetAxisRaw("Mouse X");
deltaMouse.y = Input.GetAxisRaw("Mouse Y");

Vector2 rawFrameVelocity = Vector2.Scale(deltaMouse, Vector2.one * sensitivityRotate);
velocityFrame = Vector2.Lerp(velocityFrame, rawFrameVelocity, 1f / smoothMove);
velocity += velocityFrame;
transform.localRotation = Quaternion.Euler(-velocity.y, velocity.x, 0);

获取键盘输入值控制移动。

moveX = Input.GetAxis("Horizontal");
moveY = Input.GetAxis("Vertical");

Vector3 dirMove = transform.TransformDirection(new Vector3(moveX, 0, moveY));
dirMove = dirMove.normalized;
Vector3 motion = speedMove * Time.deltaTime * dirMove;
controller.SimpleMove(motion);

使用Character Controller 组件来进行移动控制的优势是Character Controller 自带碰撞检测。只需给场景添加碰撞体,移动过程中无需再进行额外的碰撞判断。

Character Controller 的SimpleMove 和Move 区别在于有无重力效果。SimpleMove 有重力效果无法实现跳跃,Move 无重力效果可进行跳跃,也就意味着使用SimpleMove 进行移动时需给地面添加碰撞体。同时SimpleMove 和Move 的返回值也不同,SimpleMove 返回的是当前Character Controller 是否接触到地面,Move 返回的是当前Character Controller 碰撞类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值