Search code examples
c#visual-studiounity-game-engineunityscriptunity3d-2dtools

UNITY 2D: Player flying when space/mousebutton is holded


So basicy i need my character to go up when space or mousebutton are pressed. I added rigbody 2d and box colider 2d to my gameobject (player). The problem is when I hit space or mousebuttonit only jump not constantly moving up.

Here is my code:

using UnityEngine;
using System.Collections;

public class PixelMovement : MonoBehaviour {

    Vector3 velocity = Vector3.zero;
    public Vector3 PressVelocity;
    public float maxSpeed = 5f;
    public float fowardSpeed = 1f;
    public float jumpForce;

    bool didPress = false;

    // Use this for initialization
    void Start () {

    }

    //Do Graphic & Input updates
    void Update()
    {
        if (Input.GetKey(KeyCode.Space) || Input.GetMouseButton(0))
        {
            didPress = true;
        }
    }

    //Do physics engine updates here
    void FixedUpdate()
    {
        velocity.x = fowardSpeed;
        if (didPress == true)
        {
            didPress = false;
            velocity += PressVelocity * Time.deltaTime *jumpForce;

        }

        velocity = Vector3.ClampMagnitude(velocity, maxSpeed);
        transform.position += velocity * Time.deltaTime;
    }
}

Solution

  • Ok this works for me. Thanks everyone for help :)

    using UnityEngine;
    using System.Collections;
    
    public class PixelMovement : MonoBehaviour {
    
        public float playerSpeed;
        public Vector3 gravity;
        public float maxSpeed = 5f;
        Vector3 velocity = Vector3.zero;
        public float fowardSpeed = 1f;
    
        bool didPress = false;
    
        void Update()
        {
            if (Input.GetKey(KeyCode.Space) || Input.GetMouseButton(0))
            {
                didPress = true;
            }
            else
            {
                didPress = false;
            }
        }
    
        void FixedUpdate()
        {
            velocity.x = fowardSpeed;
            transform.position += velocity * Time.deltaTime;
            if (didPress == true)
            {
    
                float amntToMove1 = playerSpeed * Time.deltaTime;
                transform.Translate(Vector3.up * amntToMove1);
            }
            velocity = Vector3.ClampMagnitude(velocity, maxSpeed);
            transform.position += velocity * Time.deltaTime;
        }
    }