所以我试图创造一个逼真的蹦床跳跃,而不是让玩家从蹦床上摔下来,然后弹起,同时让玩家在接触蹦床时立即射击,并在相对重力的作用下下降。
我哪里出了问题?我能做些什么来解决它?
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class small_bounce_script: MonoBehaviour {
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
private Vector3 bounce = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
if (bounce.sqrMagnitude > 0) {
moveDirection = bounce;
bounce = Vector3.zero;
} else {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
}
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
void OnTriggerEnter(Collider other) {
Debug.Log ("Controller collider hit");
Rigidbody body = other.attachedRigidbody;
// Only bounce on static objects...
if ((body == null || body.isKinematic) && other.gameObject.controller.velocity.y < -1f) {
float kr = 0.5f;
Vector3 v = other.gameObject.controller.velocity;
Vector3 n = other.normal;
Vector3 vn = Vector3.Dot(v,n) * n;
Vector3 vt = v - vn;
bounce = vt -(vn*kr);
}
}
}
那么您的Y坐标Y与OnTriggerStay
期间的正弦函数成比例。当Y的一阶导数为余弦函数时,Y方向上的速度v,而X和Z速度保持不变。
y(t)=yMax*sin(f*t)
v(t)=yMax*f*cos(f*t)
考虑到能量守恒,我们有:
E=0.5*m*vMax²=0.5*k*yMax²
=>yMax=±SQRT(k/m)*vMax
- vMax:=撞击蹦床时Y方向的速度。±因为着陆和启动
- yMax:=当v==0时的最大振幅,即玩家在返回前下沉的深度
- k:=定义蹦床行为的弹簧常数,即其强度
- m:=玩家的质量
- f:=SQRT(k/m)
所以你所需要做的就是摆弄弹簧常数,在你的Update
方法中有这样的东西:
Vector3 velocity = rigidbody.velocity;
float elapsedTime = Time.time - timestampOnEnter;
velocity.y = YMax * FConst * Mathf.cos (FConst * elapsedTime);
rigidbody.velocity = velocity;
成员vartimestampOnEnter
取在OnTriggerEnter
中,FConst是我们在数学部分中称为f的常数。