Jump to content

C# code not working for making the player Jump (UNITY)

Hey guys I'm having some trouble with my code to make the player jump and need some assistance, when i press space its like its trying to jump but it doesn't jump, like its restricted. Here is the movement script: 

public class PlayerMovement : MonoBehaviour {
	public float maxSpeed = 3f;
	public float speed = 50f;
	public float jumpPower = 150f;

	public bool grounded;

	private Rigidbody2D Rgb;
	// Use this for initialization
	void Start () {
		Rgb = GetComponent<Rigidbody2D> ();
	}
		
	// Update is called once per frame
	void Update () {
		if (Input.GetButtonDown ("Jump") && grounded) {
			grounded = false;
			Rgb.AddForce (Vector2.up * jumpPower);
		}
	}

	void FixedUpdate () {
		float Haxis = Input.GetAxis ("Horizontal");

		//moves the player by adding force
		Rgb.AddForce ((Vector2.right * speed) * Haxis);

		//limits the players speed in both directions
		if (Rgb.velocity.x > maxSpeed) {
			Rgb.velocity = new Vector2 (maxSpeed, Rgb.velocity.y);
		} else if (Rgb.velocity.x < -maxSpeed) {
			Rgb.velocity = new Vector2 (-maxSpeed, Rgb.velocity.y);
		}
	}
}

Here is the ground check script: 

public class GroundCheck : MonoBehaviour {
	private PlayerMovement player;

	// Use this for initialization
	void Start () {
		player = gameObject.GetComponentInParent<PlayerMovement> ();
	}
          
	void OnTriggerEnter2D (Collider2D col) {
		player.grounded = true;
		Debug.Log ("isGrounded");
	}

	void OnTriggerStay2D (Collider2D col) {
		player.grounded = true;
	}

	void OnTriggerExit2D (Collider2D col) {
		player.grounded = false;
	}
}

Any help will be appreciated :) 

Link to comment
Share on other sites

Link to post
Share on other sites

8 minutes ago, manlykeweaver465 said:

Hey guys I'm having some trouble with my code to make the player jump and need some assistance, when i press space its like its trying to jump but it doesn't jump, like its restricted. Here is the movement script: 


public class PlayerMovement : MonoBehaviour {
	public float maxSpeed = 3f;
	public float speed = 50f;
	public float jumpPower = 150f;

	public bool grounded;

	private Rigidbody2D Rgb;
	// Use this for initialization
	void Start () {
		Rgb = GetComponent<Rigidbody2D> ();
	}
		
	// Update is called once per frame
	void Update () {
		if (Input.GetButtonDown ("Jump") && grounded) {
			grounded = false;
			Rgb.AddForce (Vector2.up * jumpPower);
		}
	}

	void FixedUpdate () {
		float Haxis = Input.GetAxis ("Horizontal");

		//moves the player by adding force
		Rgb.AddForce ((Vector2.right * speed) * Haxis);

		//limits the players speed in both directions
		if (Rgb.velocity.x > maxSpeed) {
			Rgb.velocity = new Vector2 (maxSpeed, Rgb.velocity.y);
		} else if (Rgb.velocity.x < -maxSpeed) {
			Rgb.velocity = new Vector2 (-maxSpeed, Rgb.velocity.y);
		}
	}
}

Here is the ground check script: 


public class GroundCheck : MonoBehaviour {
	private PlayerMovement player;

	// Use this for initialization
	void Start () {
		player = gameObject.GetComponentInParent<PlayerMovement> ();
	}
          
	void OnTriggerEnter2D (Collider2D col) {
		player.grounded = true;
		Debug.Log ("isGrounded");
	}

	void OnTriggerStay2D (Collider2D col) {
		player.grounded = true;
	}

	void OnTriggerExit2D (Collider2D col) {
		player.grounded = false;
	}
}

Any help will be appreciated :) 

Perhaps you aren't adding enough force. This is just my initial interpretation of the code. ALSO, I notice that you are working with a "horizontal" force from Unity's API, but you are trying to jump, which by logic would seem to be vertical?

 

What I would do is create a new Vector2 and pass in '0' for horizontal force and then "Haxis" for the vertical. Except you should probably name that "V_Axis" if you are going to program it like that. There is a chance that I am wrong however, maybe Unity doesn't define horizontal and vertical in the same orientation?

Hope this helps,

Friendly LTT member.

Link to comment
Share on other sites

Link to post
Share on other sites

Also, it seems as though you are trying to implement multiple features at a single time. It is probably a good idea just to implement the jumping mechanic. Now looking at your code, I think that you might have an issue with your trigger methods. If they are called too fast, then it's possible that it's calling player.grounded equate to true before it ever leaves.

 

This is also made worse by the fact that you are doing movement by adding force. So the movement won't be as immediate.

 

Again, Hope this Helps.

Link to comment
Share on other sites

Link to post
Share on other sites

4 minutes ago, Undertaker225 said:

Also, it seems as though you are trying to implement multiple features at a single time. It is probably a good idea just to implement the jumping mechanic. Now looking at your code, I think that you might have an issue with your trigger methods. If they are called too fast, then it's possible that it's calling player.grounded equate to true before it ever leaves.

 

This is also made worse by the fact that you are doing movement by adding force. So the movement won't be as immediate.

 

Again, Hope this Helps.

thanks, ill give it a try now 

Link to comment
Share on other sites

Link to post
Share on other sites

10 minutes ago, Undertaker225 said:

Also, it seems as though you are trying to implement multiple features at a single time. It is probably a good idea just to implement the jumping mechanic. Now looking at your code, I think that you might have an issue with your trigger methods. If they are called too fast, then it's possible that it's calling player.grounded equate to true before it ever leaves.

 

This is also made worse by the fact that you are doing movement by adding force. So the movement won't be as immediate.

 

Again, Hope this Helps.

what would be a better way of doing movement ? 

Link to comment
Share on other sites

Link to post
Share on other sites

5 minutes ago, manlykeweaver465 said:

thanks, ill give it a try now 

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

public class playerMovement : MonoBehaviour {

    public float speed;
    public Rigidbody rb;

    void Start()
    {
        speed = 5;
        rb = gameObject.GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        float moveVertical = Input.GetAxis("Vertical");

        Vector2 jump = new Vector2(0, moveVertical);
        rb.velocity = jump * speed;

    }
}

This is what a basic jump mechanic will do for you. Basically, what this says is that when the user (or in the testing phases, you) presses the 'W' or the up arrow key, then they will be able to move in that direction. However, this doesn't account for gravity and is a continuous jump. I thought that this might help you with a basic understanding of the jump mechanic. If you knew this already then I apologize.

Link to comment
Share on other sites

Link to post
Share on other sites

It depends on the game. Some games do what you do and use physics-based movement. That's totally up to you. Sometimes, you can just edit the velocity of a Rigidbody directly. So I was wrong to say that physics is a "bad" way to do movement of any sort. I've obviously just spent way too much time playing MMORPG games Ha. So I have a severely bias opinion. A lot of people love Physics-based movement.

 

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, Undertaker225 said:

It depends on the game. Some games do what you do and use physics-based movement. That's totally up to you. Sometimes, you can just edit the velocity of a Rigidbody directly. So I was wrong to say that physics is a "bad" way to do movement of any sort. I've obviously just spent way too much time playing MMORPG games Ha. So I have a severely bias opinion. A lot of people love Physics-based movement.

 

ahh okay, this is all for my school project (doing a 2D platformer) so im just practicing before i start developing 

Link to comment
Share on other sites

Link to post
Share on other sites

6 minutes ago, Undertaker225 said:

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

public class playerMovement : MonoBehaviour {

    public float speed;
    public Rigidbody rb;

    void Start()
    {
        speed = 5;
        rb = gameObject.GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        float moveVertical = Input.GetAxis("Vertical");

        Vector2 jump = new Vector2(0, moveVertical);
        rb.velocity = jump * speed;

    }
}

This is what a basic jump mechanic will do for you. Basically, what this says is that when the user (or in the testing phases, you) presses the 'W' or the up arrow key, then they will be able to move in that direction. However, this doesn't account for gravity and is a continuous jump. I thought that this might help you with a basic understanding of the jump mechanic. If you knew this already then I apologize.

ive just tried this and it does work, but the player just shoots up and then slowly falls back down and if i hold it in it just goes into the air, im guessing ill be able to fix this using the ground check 

Link to comment
Share on other sites

Link to post
Share on other sites

12 minutes ago, manlykeweaver465 said:

ive just tried this and it does work, but the player just shoots up and then slowly falls back down and if i hold it in it just goes into the air, im guessing ill be able to fix this using the ground check 

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

public class playerMovement : MonoBehaviour {

    public float force;
    public Rigidbody rb;
    public bool grounded;

    void Start()
    {
        force = 500;
        rb = gameObject.GetComponent<Rigidbody>();
        grounded = true;
    }

    void FixedUpdate()
    {
        if (grounded)
        {
            grounded = false;
            rb.AddForce(gameObject.transform.up * force);
        }

    }

    void OnCollisionEnter(Collision collidingObject)
    {
        grounded = true;
    }
}

Try this. I want to apologize for just looking at the simplicity of jumping, rather than worrying about actual game mechanics. This actual saves you from having to use more than one script. Basically, we are going to add a force in the upward direction only and then multiply it by a force to give it enough power to jump. Try and see if this works for your situation.

Link to comment
Share on other sites

Link to post
Share on other sites

10 minutes ago, Undertaker225 said:

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

public class playerMovement : MonoBehaviour {

    public float force;
    public Rigidbody rb;
    public bool grounded;

    void Start()
    {
        force = 500;
        rb = gameObject.GetComponent<Rigidbody>();
        grounded = true;
    }

    void FixedUpdate()
    {
        if (grounded)
        {
            grounded = false;
            rb.AddForce(gameObject.transform.up * force);
        }

    }

    void OnCollisionEnter(Collision collidingObject)
    {
        grounded = true;
    }
}

Try this. I want to apologize for just looking at the simplicity of jumping, rather than worrying about actual game mechanics. This actual saves you from having to use more than one script. Basically, we are going to add a force in the upward direction only and then multiply it by a force to give it enough power to jump. Try and see if this works for your situation.

That works well thanks :D, ive added an if statement for the user input, then nested the grounded if statement so it  checks if grounded = true when i press a key.

	void FixedUpdate () {
		if (Input.GetKeyDown(KeyCode.A)) {
			if (grounded) {
			grounded = false;
			Rgb.AddForce (gameObject.transform.up * force);
			}
		}

PS. the key code a was just for testing, ill change that to the key i want later :P 

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, manlykeweaver465 said:

That works well thanks :D, ive added an if statement for the user input, then nested the grounded if statement so it  checks if grounded = true when i press a key.


	void FixedUpdate () {
		if (Input.GetKeyDown(KeyCode.A)) {
			if (grounded) {
			grounded = false;
			Rgb.AddForce (gameObject.transform.up * force);
			}
		}

PS. the key code a was just for testing, ill change that to the key i want later :P 

Lol Whoops. that's what I keep for coding and working at the same time. My bad xD

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, Undertaker225 said:

Lol Whoops. that's what I keep for coding and working at the same time. My bad xD

np, Thanks for taking time to help me, ill read through the code to make sure i understand all of it before moving on :) 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×