Hey guys!
This is my first question on UnityAnswers. I’m new to game programming as well as the Unity engine and I’m currently working on my first game.
I’ve gotten my player to move around and jump, but the jumping is a bit jerky. The player rises a certain distance instantly, but then comes back to the ground normally, through gravity.
I would like the player to rise into the air a bit more gradually. As of now it seems to all be happening in one frame.
Here’s the code I’m using.
using UnityEngine;
using System.Collections;
public class PlayerControl : MonoBehaviour {
// Running speed to be changed in inspector - this will be a part of the vector 'running'
public float speed = 1.0f;
// Jumping force to be changed in inspector - will be used to AddForce to the 2D RigidBody
public float jump = 1.0f;
// To detect if the player is on the ground or not
bool onGround = true;
// The vector to store out movement
private Vector2 running;
// Use for physics frame updates
void FixedUpdate()
{
// Detects use of the right or left keys to apply a + or - 1 value to running.x
running.x = Input.GetAxis ("Horizontal") * speed;
// Executes running function through velocity
GetComponent<Rigidbody2D>().velocity = running;
// Listens for the player pressing the up button
if(Input.GetKeyUp("up") && onGround)
{
// The character is now no longer on the ground
onGround = false;
// Makes the character jump
GetComponent<Rigidbody2D> ().AddForce(new Vector2 (0, jump), ForceMode2D.Impulse);
}
}
// Checks if the player is touching the ground
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Ground")
onGround = true;
}
}
The player has a 2D RigidBody, no kinematics or triggers. As of now, my ‘jump’ variable is set at 50 and my gravity scale is 10.
Any help will be appreciated greatly and even if you want to comment on my code in general, I’m open to feedback. =)
Thanks in advance!