我的角色在平坦的表面上弹跳,如图所示。但是当地板弯曲时它不会跳。我不知道我在做什么错。我的角色在平坦的地面上跳跃。但是当地面不平坦时我的角色不会跳跃。
我的跳转脚本在这里:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class WalkJumpFire : MonoBehaviour {
public CharacterController2D kontroller;
Rigidbody2D rb;
float dirX;
[SerializeField]
float moveSpeed = 5f, jumpForce = 800f, bulletSpeed = 500f;
bool facingRight = true;
Vector3 localScale;
public Transform barrel;
public Rigidbody2D bullet;
// Use this for initialization
void Start () {
localScale = transform.localScale;
rb = GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void Update () {
dirX = CrossPlatformInputManager.GetAxis ("Horizontal");
if (CrossPlatformInputManager.GetButtonDown ("Jump"))
Jump ();
if (CrossPlatformInputManager.GetButtonDown ("Fire1"))
Fire ();
}
void FixedUpdate()
{
rb.velocity = new Vector2 (dirX * moveSpeed, rb.velocity.y);
}
void LateUpdate()
{
CheckWhereToFace ();
}
void CheckWhereToFace()
{
if (dirX > 0)
facingRight = true;
else
if (dirX < 0)
facingRight = false;
if (((facingRight) && (localScale.x < 0)) || ((!facingRight) && (localScale.x > 0)))
localScale.x *= -1;
transform.localScale = localScale;
}
void Jump()
{
if (rb.velocity.y == 0)
rb.AddForce (Vector2.up * jumpForce);
}
void Fire()
{
var firedBullet = Instantiate (bullet, barrel.position, barrel.rotation);
firedBullet.AddForce (barrel.up * bulletSpeed);
}
}
答案 0 :(得分:3)
如@derHugo所述,使用刚体在地面上的状态(通过isGrounded方法)来激发跳跃:
public bool isGrounded;
//During collisions you would still want your object to jump, such as jumping while touching the corner of a wall, so:
void OnCollisionStay()
{
isGrounded = true;
}
//Your not able to jump right after collision: (Also add layers so your object can't pass through walls or entities in the game)
void OnCollisionExit()
{
isGrounded = false;
}
//Jump only if your object is on ground:
void Jump()
{
if(isGrounded)
{
rb.AddForce (Vector2.up * jumpForce);
//set it to false again so you can't multi jump:
isGrounded = false;
}
}