所以我试图创造一个逼真的蹦床跳跃,而不是让玩家从蹦床上掉下来然后再弹回,同时允许玩家在与蹦床接触时立即射击并降低相对重力。
我哪里出错了,我该怎么做才能解决它?
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);
}
}
}
答案 0 :(得分:1)
蹦床像spring device一样反应。假设重力在Y方向,蹦床表面在X,Z平面上定位。
然后您的Y坐标 y 与OnTriggerStay
期间的正弦函数成比例。 Y方向上的速度 v 作为y的一阶导数是余弦函数,而X和Z速度保持不变。
y(t)= yMax * sin(f * t)
v(t)= yMax * f * cos(f * t)
考虑到节约能源,我们有:
E = 0.5 * m * vMax 2 = 0.5 * k * yMax 2 =&GT; yMax =±SQRT(k / m)* vMax
所以你需要做的就是玩弹簧常数并在你的Update
方法中使用类似的东西:
Vector3 velocity = rigidbody.velocity;
float elapsedTime = Time.time - timestampOnEnter;
velocity.y = YMax * FConst * Mathf.cos (FConst * elapsedTime);
rigidbody.velocity = velocity;
成员var timestampOnEnter
取自OnTriggerEnter
,FConst是我们在数学部分中调用 f 的常量。