【问题标题】:trampoline unity code not working蹦床统一代码不起作用
【发布时间】:2014-02-19 17:14:23
【问题描述】:

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

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

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

    }

}

}

【问题讨论】:

    标签: unity3d gravity trampolines


    【解决方案1】:

    蹦床的反应就像spring device。假设重力在 Y 方向,蹦床表面位于 X、Z 平面。

    那么您的 Y 坐标 yOnTriggerStay 期间与正弦函数成正比。 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;
    

    成员变量timestampOnEnter取自OnTriggerEnter,FConst是我们在数学部分称为f的常数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-27
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 2014-12-30
      • 2010-09-16
      • 2016-03-24
      相关资源
      最近更新 更多