![](/img/trans.png)
[英]Unity 2d Character moves and jumps to specific positions with UI buttons
[英]The character jumps super high at it's first jump, then it jumps normally. How can I fix it? (Unity 2D)
所以这基本上就是这里的问题。 我正在使用物理学创建一个跳转脚本。 这是代码。 关于如何解决它的任何想法? 我还没有尝试任何重要的事情......只是一些小的变化,因为我不知道该怎么做。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
bool canjump = false;
void Start()
{
}
void Update()
{
if (Input.GetKey("left"))
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(-40000 * Time.deltaTime, 0));
}
if (Input.GetKey("right"))
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(40000 * Time.deltaTime, 0));
}
if (Input.GetKeyDown("up") && canjump == true)
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 4000000 * Time.deltaTime));
}
}
void OnTriggerEnter2D()
{
canjump = true;
}
void OnTriggerExit2D()
{
canjump = false;
}
}
PD:调用 OnTriggerEnter && Exit 是因为我将触发器放在平台上方。 对不起我的英语,我不是英语:P 在此先感谢。
对于初学者,您应该将物理内容放在 FixedUpdate() 中,并在 Update() 中输入,这是未经测试的:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
bool jump = false;
bool canjump = false;
void Start()
{
}
void FixedUpdate() {
if(jump)
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 4000000 * Time.deltaTime));
jump = false;
}
}
void Update()
{
if (Input.GetKey("left"))
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(-40000 * Time.deltaTime, 0));
}
if (Input.GetKey("right"))
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(40000 * Time.deltaTime, 0));
}
if (Input.GetKeyDown("up") && canjump == true)
{
jump = true;
}
}
void OnTriggerEnter2D()
{
canjump = true;
}
void OnTriggerExit2D()
{
canjump = false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.