Help with a simple jump script
I am writing a basic player controller and I am running into problems with my jump script. When I press spacebar, nothing happens.
I have this code in my update:
//jump if player presses space bar
if(Input.GetKeyDown(KeyCode.Space)){
Jump();
}
And this is the actual jump method:
//performs a jump
public void Jump(){
Vector3 up = transform.TransformDirection(Vector3.up);
rigidbody.AddForce(up*jumpForce);
}
What am I doing wrong here? Thanks!
Answer by aldonaletto · Oct 29, 2012 at 11:23 PM
You're probably using a small jumpForce: AddForce in the default mode applies the force during a single physics cycle, and the result is an increase in velocity in the force direction proportional to the time the force is applied. You could use ForceMode.Impulse, for instance:
rigidbody.AddForce(up * jumpForce, ForceMode.Impulse);
The Impulse mode concentrate in a single physics cycle all the acceleration the body would experience if the force were applied during one second. Another easier alternative is to directly add the desired velocity to the rigidbody:
rigidbody.velocity += up * jumpSpeed; // jumpSpeed could be 8.0f, for instance
In any case, notice that you're transforming the up direction to the rigidbody space - it will jump to its local up direction, what may seem weird when the character isn't upright. If this is a problem, just use Vector3.up instead of up.
NOTE: The whole thing only makes sense if your character is a rigidbody. If it's a CharacterController, forget about forces and use the example script supplied by the docs in Move.
using UnityEngine;
using System.Collections;
//Player $$anonymous$$ovment Script
public class Controls : $$anonymous$$onoBehaviour {
public float Speed = 5.0f;
//Updates Every frame
void Update () {
//Forward $$anonymous$$ovement
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.W)) {
transform.Translate(Vector3.forward * Speed * Time.deltaTime);
}
//Backward $$anonymous$$ovement
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.S)) {
transform.Translate(Vector3.back * (Speed - 2) * Time.deltaTime);
}
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.A)) {
transform.Translate(Vector3.left * Speed * Time.deltaTime);
}
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.D)) {
transform.Translate(Vector3.right * Speed * Time.deltaTime);
}
if (Input.Get$$anonymous$$eyDown ("space")) {
Vector3 up = transform.TransformDirection (Vector3.up);
rigidbody.AddForce (up * 5, Force$$anonymous$$ode.Impulse);
}
}
}
It shows: 'UnityEngine.Component' does not contain a definition for 'AddForce' and no extension method 'AddForce' accepting a first argument of type 'UnityEngine.Component' could be found
Your answer
Follow this Question
Related Questions
Why won't my character jump smoothly? 0 Answers
Character landing 0 Answers
how to jump in a 2D game 2 Answers
Jump logic issues 0 Answers
Rigidbody2D.velocity Interupts Rigidbody2D.AddForce in 2D Platformer 0 Answers