c# - 如何使用字符控制器在 Unity3d 的 C# 脚本中添加“跳转”?
问题描述
我让角色可以朝 8 个方向行走,但我不知道如何添加“跳跃”以使一切正常...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public CharacterController controller;
public float speed;
float turnSmoothVelocity;
public float turnSmoothTime;
void Update() {
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f) {
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
controller.Move(direction * speed * Time.deltaTime);
}
}
}
解决方案
无需计算角色的角度和旋转,因为当您使用 CharacterController 类时,Unity 已经为您计算了这些。
要跳跃,您可能需要为跳跃动作分配一个按钮。然后,您可以检查Update
是否每帧都按下了跳跃按钮。您可以使用类似的东西并将其添加到代码中的移动命令中:
public float jumpSpeed = 2.0f;
public float gravity = 10.0f;
private Vector3 movingDirection = Vector3.zero;
void Update() {
if (controller.isGrounded && Input.GetButton("Jump")) {
movingDirection.y = jumpSpeed;
}
movingDirection.y -= gravity * Time.deltaTime;
controller.Move(movingDirection * Time.deltaTime);
}
推荐阅读
- push-notification - 我们可以增加谷歌控制台项目中的主题和订阅数量吗?
- jakarta-ee - JavaEE:注入 @Alteriative 到 Insance
没有默认实现 - ruby-on-rails - 如何使用 rolify gem 显示与用户关联的角色名称?
- angular - map() 中的拼接函数只删除数组的一半
- python - Tkinter Gui 没有出现
- c# - 如何转换 ISearchResponse
到 IEnumerable 在c#中 - google-apps-script - Apps 脚本返回“无效的 HTML 内容”
- bash - 通过unix检查作业是否完成
- css - 网格列 fr 不适用
- java - 如何getCount多私有int