1

所以我试图创建一个逼真的蹦床跳跃,而不是玩家从蹦床上掉下来然后弹弓弹回来,而是让玩家在接触蹦床时立即射击并下降相对重力。

我哪里出错了,我能做些什么来解决它?

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);

    }

}

}

4

1 回答 1

1

蹦床的反应就像一个弹簧装置。假设重力在 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² = 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的常数。

于 2014-02-19T19:09:53.907 回答