gpt4 book ai didi

c# - Unity 2D 为什么我的角色在地面不平坦时不会跳跃?

转载 作者:行者123 更新时间:2023-12-04 10:51:58 26 4
gpt4 key购买 nike

我的角色在平面上弹跳,如图所示。但是本地板弯曲时它不会跳。我不知道我做错了什么。我的角色在平地上跳跃。但是本地面不平坦时,我的角色不会跳跃。

enter image description here

我的跳转脚本在这里:

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

最佳答案

正如@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;
}
}

关于c# - Unity 2D 为什么我的角色在地面不平坦时不会跳跃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59437329/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com