简体   繁体   中英

Jumping in Unity 2d

I got the moving left and right thing figured out, but i can't seem to get my player to jump. I have the code but i keep getting an error that says "The variable Player of Player.controller has not been assigned."

Here's the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player_controller : MonoBehaviour
{
    public float speed;
    // Start is called before the first frame update
    void Start()
    {
        
    }
    public Rigidbody2D Player;
    float JumpHeight = 10f;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.D))
        {
            Debug.Log("Moving Right");

            transform.Translate(Vector3.right * Time.deltaTime * speed);
        }

        if (Input.GetKey(KeyCode.A))
        {
            Debug.Log("Moving Left");

            transform.Translate(Vector3.left * Time.deltaTime * speed);
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("Jumping");

            Player.AddForce(Vector2.up * JumpHeight, ForceMode2D.Impulse);
        }    
    }
}

If the player has a rigidbody component, you can reference it in the Awake() method. If there isn't, just add the component

private void Awake() {
    Player = GetComponent<Rigidbody2D>();
}

Or else just drag the rigidbody component to its slot in the inspector

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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