我正在尝试使用c#为我的平台游戏统一制作跳跃垫。
我很困惑,如何使用触发器为其他gameObject加力?
在无效开始中使用rb = gameobject.getcomponent<rigidbody>
尝试过,没有工作。
这是我最接近我期望的代码
public float force = 1500f;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
other.GetComponent<Rigidbody>().AddForce(Vector3.up * force * Time.deltaTime);
Debug.Log("trigger!");
}
}
我希望如果我的球员落在扳机上,它将使他向上发动,但不会。我还应注意,控制台日志显示“触发!”因此存在错误和强制。
没有错误消息。
答案 0 :(得分:4)
Time.deltaTime是一个很小的数字,一次调用该函数就不需要它。您也可以尝试other.GetComponent<Rigidbody>().AddForce(Vector3.up * force, ForceMode.VelocityChange);
您可以在此处了解有关AddForce方法的更多信息:Rigidbody.AddForce
答案 1 :(得分:0)
我知道我来晚了,但是您可以尝试使用游戏中的跳跃动作。我的意思是,如果他按空格键,您就使他跳了。您可以重复使用。
那是我的跳跃
private void Jump()
{
if (grounded && readyToJump)
{
readyToJump = false;
//Add jump forces
rb.AddForce(Vector2.up * jumpForce * 1.5f);
rb.AddForce(normalVector * jumpForce * 0.5f);
//If jumping while falling, reset y velocity.
Vector3 vel = rb.velocity;
if (rb.velocity.y < 0.5f)
rb.velocity = new Vector3(vel.x, 0, vel.z);
else if (rb.velocity.y > 0)
rb.velocity = new Vector3(vel.x, vel.y / 2, vel.z);
Invoke(nameof(ResetJump), jumpCooldown);
}
}
现在您可以制作这样的东西
private void OnCollisionEnter(Collision collision)
{
jumpPad JumpPad = collision.collider.GetComponent<jumpPad>();
if (JumpPad != null)
{
//Add jump forces
rb.AddForce(Vector2.up * jumpPadForce * 1.5f);
rb.AddForce(normalVector * jumpPadForce * 0.5f);
//If jumping while falling, reset y velocity.
Vector3 vel = rb.velocity;
if (rb.velocity.y < 0.5f)
rb.velocity = new Vector3(vel.x, 0, vel.z);
else if (rb.velocity.y > 0)
rb.velocity = new Vector3(vel.x, vel.y / 2, vel.z);
}
}
这是最简单,最快的解决方案。 只需施加一个新的跳跃力,然后将其称为“跳跃垫力”即可。 就是这样。