[英]Unity5 : 2D Platformer : Jumping with to different height
我正在尝试在C#中实现字符跳转,但我希望他跳转到不同的高度,具体取决于您按住“跳转”按钮的方式。
例如,如果您瞬间击中空间-跳得不会很高。反之,角色将跳得更高,但跳得有限。
这是我的代码:
private Rigidbody2D rb;
private Transform lowerPoint;
private new SpriteRenderer renderer;
private Animator anim;
private Transform spawPosition;
[SerializeField]
float speed = 3f;
[SerializeField]
float jumpForce = 3f;
[SerializeField]
Image backgroundImage;
[SerializeField]
LayeredSpikes script;
float secondJumpForce;
[SerializeField]
float additionalVelocity;
const float ADDITION_VELOCITY_LIMIT = 0.9f;
bool isGrounded;
bool isAlive;
bool hasSecondJump;
void Awake()
{
rb = GetComponent<Rigidbody2D> ();
renderer = GetComponent<SpriteRenderer> ();
lowerPoint = GetComponentInChildren<Transform> ();
anim = GetComponent<Animator> ();
spawPosition = GameObject.FindGameObjectsWithTag ("Respawn")[0].GetComponent<Transform> ();
}
void Start()
{
ResetVelocity ();
isGrounded = false;
isAlive = true;
hasSecondJump = true;
Spawn ();
secondJumpForce = jumpForce * 0.75f;
}
void Update()
{
if (isAlive)
{
if (isGrounded)
{
AnimState = AnimationState.Idle;
hasSecondJump = true;
additionalVelocity = 0f;
}
if (Input.GetButtonDown ("Jump"))
{
Jump ();
}
if (Input.GetButton ("Jump")
&& additionalVelocity <= ADDITION_VELOCITY_LIMIT)
{
additionalVelocity += ADDITION_VELOCITY_LIMIT / 3;
rb.AddForce( Vector2.up * additionalVelocity );
}
if (Input.GetButton ("Horizontal"))
{
Run ();
}
}
}
private void Jump()
{
AnimState = AnimationState.Jump;
float force;
if (isGrounded)
{
force = jumpForce;
}
else
{
if (hasSecondJump)
{
ResetVelocity ();
force = secondJumpForce;
hasSecondJump = false;
}
else
{
force = 0f;
}
}
rb.AddForce (Vector2.up * force, ForceMode2D.Impulse);
if (force != 0f)
{
//script.Trigger ();
}
}
void ResetVelocity()
{
rb.velocity = Vector2.zero;
additionalVelocity = 0f;
}
我正在尝试在跳跃中间增加力量,但没有结果。
乍一看,我可以观察到您的布尔变量isGrounded始终为false 。 这个问题很棘手,因为实际上是您的第二次跳跃有效,但第一次跳跃却没有,这就是为什么您很难检测到它!
将变量isGrounded = true设置为Start()的默认值,然后在第一次跳转时将isGrounded = false设置。
然后,您可以使用Colliders来检测角色何时回到地面,如果是,则需要将isGrounded变量设为 isGrounded 公用 。
希望我能提供帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.