- Home /
First Person Jump Script Not Working
Hello all! I am working on my first Unity game, and I'm having some trouble.
I want my object to jump on a "W" key press, but I cannot get it to work.
Here is my code: (Javascript)
var jumping : boolean = false;
var timer=5;
function Update () {
//Should skip this before it is pressed
if (jumping == true){
timer+=-.1 * Time.deltaTime;
}
//Should skip this before it is pressed
if (timer == 0){
timer=5;
jumping = false;
if (Input.GetAxis("Vertical") > 0 && jumping == false) {
transform.Translate(0, 10 * Time.deltaTime * Input.GetAxis("Vertical"),0);
jumping = true;
}
}
//transform.Translate(0,0, 100 * Time.deltaTime);
}
If I am way off base on how to do this, what is an easier way?
I'd like to stay away from character controllers to do this.
Here is a picture of what I'm thinking.

Answer by iwaldrop · Feb 13, 2013 at 04:35 AM
Just because you want to stay away from the Character Controller doesn't mean you can't take advantage of physics.
Attach a rigidbody and collider to your GameObject (if you haven't already). Then, in your code, add the following
public string walkableTag;
void Update()
{
if (!jumping && Input.GetAxis("Vertical") > 0)
{
rigidbody.AddForce(Vector3.up * 10, ForceMode.Impulse);
jumping = true;
}
}
void OnCollisionEnter(Collision collision)
{
foreach (ContactPoint c in collision.contacts)
{
if (c.otherCollider.tag == walkableTag)
jumping = false;
}
}
Alternatively you could use
if (!jumping && Input.GetButtonDown("Jump"))
The code you provided basically makes the jumping work, but I have run across another problem.
When I add the line that I had commented out in the original code, the object accelerates, yet bounces off on a collision with the floor.
transform.Translate(0,0, 100 * Time.deltaTime);
How can I keep the object on the floor when it is just accelerating, and allow it to jump freely using your code?
Add this line in your awake
void Awake()
{
rigidbody.freezeRotation = true;
}
Your answer