简体   繁体   English

unity 2d 跳跃脚本

[英]Unity 2d jumping script

Does anyone have a good jumping script for 2d games in unity?有没有人有一个很好的统一的 2d 游戏跳跃脚本? The code I have works but still is far from jumping, it looks like it is flying.我的代码有效,但距离跳跃还很远,它看起来像是在飞行。

using UnityEngine;
using System.Collections;

public class movingplayer : MonoBehaviour {

public Vector2 speed = new Vector2(10,10);

private Vector2 movement = new Vector2(1,1);

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    float inputX = Input.GetAxis ("Horizontal");
    float inputY = Input.GetAxis ("Vertical");

    movement = new Vector2(
        speed.x * inputX,
        speed.y * inputY);

    if (Input.GetKeyDown ("space")){
                         transform.Translate(Vector3.up * 260 * Time.deltaTime, Space.World);
                 } 

}
void FixedUpdate()
{
    // 5 - Move the game object
    rigidbody2D.velocity = movement;
    //rigidbody2D.AddForce(movement);

}
}

Usually for jumping people use Rigidbody2D.AddForce with Forcemode.Impulse .通常对于跳跃的人使用Rigidbody2D.AddForceForcemode.Impulse It may seem like your object is pushed once in Y axis and it will fall down automatically due to gravity.看起来你的物体在 Y 轴上被推动一次,它会由于重力而自动落下。

Example:例子:

rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);

The answer above is now obsolete with Unity 5 or newer.上面的答案现在在 Unity 5 或更新版本中已经过时了。 Use this instead!用这个代替!

GetComponent<Rigidbody2D>().AddForce(new Vector2(0,10), ForceMode2D.Impulse);

I also want to add that this leaves the jump height super private and only editable in the script, so this is what I did...我还想补充一点,这使跳跃高度变得超级私密,并且只能在脚本中进行编辑,所以这就是我所做的......

    public float playerSpeed;  //allows us to be able to change speed in Unity
public Vector2 jumpHeight;

// Use this for initialization
void Start () {

}
// Update is called once per frame
void Update ()
{
    transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f);  //makes player run

    if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space))  //makes player jump
    {
        GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);

This makes it to where you can edit the jump height in Unity itself without having to go back to the script.这使得您可以在 Unity 本身中编辑跳跃高度,而无需返回脚本。

Side note - I wanted to comment on the answer above, but I can't because I'm new here.旁注 - 我想对上面的答案发表评论,但我不能,因为我是新来的。 :) :)

Use Addforce() method of a rigidbody compenent, make sure rigidbody is attached to the object and gravity is enabled, something like this使用刚体组件的 Addforce() 方法,确保刚体附加到对象并启用重力,像这样

gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or 
gameObj.rigidbody2D.AddForce(Vector3.up * 1000); 

See which combination and what values matches your requirement and use accordingly.查看哪种组合和哪些值符合您的要求并相应地使用。 Hope it helps希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM