所以我设法修好了我的蹦床代码,这样玩家就会像蹦床一样反弹。但是,我对此代码有两个问题。
首先,当它在蹦床上弹跳时,它基本上会将玩家直接发射到平流层,他们只是继续前进,就好像没有重力让他们失望一样。即使我在玩家刚体设置中检查了重力。
其次,即使玩家不在蹦床附近,例如在没有附加蹦床脚本代码的平台上,玩家会在游戏开始时立即投入播放。
代码如下:
using UnityEngine;
using System.Collections;
public class small_trampoline_bounce : MonoBehaviour
{
bool willBounce = false;
float bounceHeight = 10;
public Transform Player;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 velocity = Player.rigidbody.velocity;
if (willBounce)
{
Player.rigidbody.velocity = new Vector3(velocity.x, 0, velocity.z);
Player.rigidbody.AddForce(0, bounceHeight, 0, ForceMode.Impulse);
willBounce = false;
}
}
void OnCollisionEnter(Collision Trampoline)
{
if (Trampoline.gameObject.name == "Player")
{
willBounce = true;
}
}
}
这也是蹦床和播放器的当前设置状态
播放器设置: http://gyazo.com/b4d924849a86e5158361f6081948e39f.png
答案 0 :(得分:0)
我不知道这是否能解决您的问题,但也许可以尝试一下:
using UnityEngine;
using System.Collections;
public class small_trampoline_bounce : MonoBehaviour
{
float bounceHeight = 10;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnCollisionEnter(Collision Trampoline)
{
if (Trampoline.gameObject.name == "Player")
{
Vector3 velocity = Trampoline.gameObject.rigidbody.velocity;
Trampoline.gameObject.rigidbody.velocity = new Vector3(velocity.x, 0, velocity.z);
Trampoline.gameObject.rigidbody.AddForce(0, bounceHeight, 0, ForceMode.Impulse);
}
}
}
这样,addforce只会应用于击中蹦床的玩家,并且只能触发一次。它可能无法解决您的问题,因为您的代码理论上应该有效,但您永远不会知道。
答案 1 :(得分:0)
好吧,在弄乱了代码之后,我设法让它正常工作,最终结果是我结束了将代码附加到玩家角色运动员,以便当玩家与蹦床相撞时,它实现向下将整个玩家的弹跳反转到团结检查员所规定的特定高度的力。下面的代码显示了最终结果。
public float speed;
public float jumpSpeed;
public float gravity;
public Vector3 moveDirection = Vector3.zero;
public float downwardForce;
public float terminalVelocity;
public float airSpeed;
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
// is the controller on the ground?
if (controller.isGrounded)
{
//Feed moveDirection with input.
moveDirection = new Vector3 (Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical"));
moveDirection = transform.TransformDirection (moveDirection);
downwardForce = 0;
//Multiply it by speed.
moveDirection *= speed;
//Jumping
if (Input.GetButton ("Jump"))
{
downwardForce -= jumpSpeed;
}
}
else
{
if (downwardForce < terminalVelocity)
{
moveDirection *= airSpeed;
downwardForce += gravity * Time.deltaTime;
}
}
//Applying gravity to the controller
moveDirection.y -= downwardForce * Time.deltaTime;
//Making the character move
controller.Move(moveDirection * Time.deltaTime);
}
void OnTriggerEnter(Collider collider)
{
if (collider.tag == "smallTrampoline")
{
downwardForce *= -1 * collider.gameObject.transform.GetComponent<SmallTrampolineBounce> ().jumpSpeed;
}
if (collider.tag == "largeTrampoline")
{
downwardForce *= -2 * collider.gameObject.transform.GetComponent<SmallTrampolineBounce> ().jumpSpeed;
}
我还实施了airSpeed作为一种方式,当玩家空中播放时,玩家无法快速移动,而玩家根本无法移动,只是保持卡住跳跃状态。向下