赞
踩
Unity默认界面->Edit->Project Settings->Physics->Gravity->Y 这个值的默认值是-9.81,我们将其改为-40,即可获得较为真实的(类似大多fps游戏如apex legends,titanfall2,csgo)跳跃下落感,也可根据项目需求自行调整。
在之前学习人物高级移动:墙跑、爬墙、滑铲的时候没感受到问题,后来将此套代码复制到另一项目中发现下落很慢,又参考了一些文章,在检查过程中发现了这个问题(视频链接:https://www.youtube.com/watch?v=SsckrYYxcuM,国内b站搬运链接:【【Unity教程搬运】9分钟完成高级滑动 - Unity教程】 https://www.bilibili.com/video/BV1sd4y1V7tF/?share_source=copy_web&vd_source=033061353294ae0352cec4c059f20a65https://www.youtube.com/watch?v=SsckrYYxcuM)
第一遍看的时候,-9.81的重力加速度,很符合现实的数值,就很相信这个数字,觉得是其他地方的问题。但是引擎毕竟是模拟,绕了一大圈发现看的文章基本都是在说这个数值的问题,我这才想起来去横向对比一下,结果两个项目数值不一样,-40的比较真实,-9.81的下落像在月球上一样。
后来又考虑了一下会不会是跳跃给的上升冲量太大了,这里做个补充,本文跳跃使用的上升力为Force.Impulse即对应现实物理中的冲量(解释看黄字),所以又对-9.81的重力加速度下的环境降低上升力进行了测试,结果依然不行的,测试结果看下文。
Force:向刚体施加连续的力(意味着物体受到force参数的力,时间为一帧的时间),考虑其质量,即同样的力施加在越重的物体上产生的加速度越小。
Impulse:向刚体施加瞬时的力(相当于物体瞬间获得受到force参数的力影响一秒钟时间的效果),考虑其质量,即同样的力施加在越重的物体上产生的加速度越小。
因为刚体代码是执行在fixedupdate里面的,所以同样的里用impulse等于瞬间执行了50次force
测试录制均由1秒60帧的质量进行拍摄
- using System.Collections;
- using System.Collections.Generic;
- using TMPro;
- using UnityEngine;
- using UnityEngine.UI;
-
- public class PlayerMovement : MonoBehaviour
- {
-
- public float groundDrag;
-
-
- [Header("Jumping")]
- public float jumpForce;
- public float jumpCoolDown;
- bool readyToJump = true;
-
-
- [Header("Keybinds")]
- public KeyCode jumpKey = KeyCode.Space;
-
- [Header("Ground Check")]
- public float playerHeight;
- public LayerMask whatIsGrounded;
- public bool grounded;
-
-
- Rigidbody rb;
-
- public TextMeshProUGUI text_Speed;
- public TextMeshProUGUI text_mode;
-
- private RaycastHit groundHit;
-
- // Start is called before the first frame update
- void Start()
- {
- text_Speed.color = Color.green;
- text_Speed.fontSize = 24;
-
- rb = GetComponent<Rigidbody>();
- rb.freezeRotation = true;
- readyToJump = true;
- }
-
- // Update is called once per frame
- void Update()
- {
-
- text_Speed.text = "speed: " + rb.velocity.magnitude;
- //cast if on ground
- grounded = Physics.SphereCast(transform.position, 0.45f, Vector3.down, out groundHit, playerHeight * 0.3f, whatIsGrounded);
- Debug.Log(grounded);
- MyInput();
-
- //deal with drag
- if (grounded)
- rb.drag = groundDrag;
- else
- rb.drag = 0;
- //Debug.Log(rb.drag);
- }
- private void MyInput()
- {
- //when to jump
- if (Input.GetKey(jumpKey) && readyToJump && grounded)
- {
- readyToJump = false;
-
- Jump();
- Invoke(nameof(ResetJump), jumpCoolDown);
- }
-
- }
-
-
-
-
-
- private void Jump()
- {
-
- // Debug.Log("jump");
- rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
-
- rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
- }
-
- private void ResetJump()
- {
- readyToJump = true;
- }
-
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。