- Home /
Apply gravity to my character through script.
Hi Im trying to apply gravity to my character because when he jumps you comes down really slowly its like he's on the moon. Ive tried everything I can but I cant get him to come down faster when he jumps. This is a platforming game so its like he can jump over 2 Platforms when you press Space.
Heres my script so far:
using UnityEngine;
public class Runner : MonoBehaviour
{
public static float distanceTraveled;
public float acceleration;
private bool touchingPlatform;
public Vector3 jumpVelocity;
public Vector3 Gravity;
public float gameOverY;
void Update ()
{
if(touchingPlatform && Input.GetButtonDown("Jump"))
{
rigidbody.AddForce(jumpVelocity, ForceMode.VelocityChange);
rigidbody.AddForce(Gravity, ForceMode.VelocityChange);
touchingPlatform = false;
}
distanceTraveled = transform.localPosition.x;
if(transform.localPosition.y < gameOverY)
{
Application.LoadLevel("GameOver");
}
}
void FixedUpdate()
{
if(touchingPlatform)
{
rigidbody.AddForce(acceleration, 0f, 0f, ForceMode.Acceleration);
}
}
void OnCollisionEnter()
{
touchingPlatform = true;
}
void OnCollisionExit()
{
touchingPlatform = false;
}
}
Thanks in advance.
You probably want to use AddForce(Gravity * Time.deltaTime, Force$$anonymous$$ode.Force) or AddForce(Gravity, Force$$anonymous$$ode.Impulse).
Personally I found the AddForce documentation in the Unity scripting reference to be quite confusing and not specific enough... I had to run my own tests to confirm that I was getting the correct (and frame rate independent) results.
Thanks for the answer but i tried this and it didnt make a difference. Am I putting it in the wrong function? @Huacanacha
Yeah I think it's in the wrong function - The 'AddForce(Gravity' part only gets called once, in the frame that you press the jump button.
Basically I'd just move
rigidbody.AddForce(Gravity, Force$$anonymous$$ode.VelocityChange);
Into the fixed update function, outside of any if statements. That way it will add gravity to the velocity every frame, making you fall faster.
Thanks but this makes him jump higher. Any Solutions?
What is your Gravity variable set to? Also is there a reason you're not using the built in Unity gravity? By default it's set to [0,-9.81, 0] and should apply to all non-kinematic rigidbodys.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to check if your character is falling 2D - C# 1 Answer
Jump and run on a circle (2D) 0 Answers