- Home /
Difficulty with rolling my own platformer script
I'm writing a very simple platformer, and i'm trying to get the script that controls the player right. I have the following so far:
using UnityEngine; using System.Collections;
public class PlatformerControlScript: MonoBehaviour { public float GravityStrength = 5; public float JumpStrength = 1000; public float MovementSpeed = 500; public float XTolerance = 1;
void FixedUpdate ()
{
float forceX = Input.GetAxis("Horizontal") * MovementSpeed;
rigidbody.AddForce(new Vector3(forceX, 0, 0));
}
void OnCollisionStay(Collision collisionInfo)
{
if (collisionInfo.gameObject.tag == "Lava")
{
Die();
}
if (rigidbody.velocity.x <= XTolerance && rigidbody.velocity.x >= -XTolerance) //we are still enough to do.... something
{
if (Input.GetKeyDown(KeyCode.Space))
{
rigidbody.AddForce(new Vector3(0, JumpStrength, 0));
}
}
}
void Die()
{
//TODO: add code here
}
}
There's some piping code for when i add in a lava tile to my platformer, but ignore that for now. Right now, i'm just trying to get my platformer guy to jump: If he is still on a surface, and i press space, he won't jump. The force i'm applying should be enough, yet it doesn't seem to be jumping. What's the recommended way to get something to "jump"?
Answer by spinaljack · Apr 16, 2010 at 06:10 PM
Rather than applying a force you could try directly altering the velocity:
if (Input.GetButtonDown ("Jump") && ground == true) {
rigidbody.velocity.y = 10;
}
}
The ground part is to make sure you're on the ground before you can jump (unless you have some kind of double jump). You might also want to stop auto jumping if you hold down the space key.
Answer by duck · Apr 02, 2010 at 11:18 AM
If I recall correctly, OnCollisionStay events stop happening if the rigidbody has gone to sleep. Use rigidbody.WakeUp() each FixedUpdate to keep it awake.
I added that, and it didn't help. Do you have a better suggestion for a jumping method? :)
Your answer
Follow this Question
Related Questions
Smoothing out jumping? 1 Answer
Wall Jumping Help 1 Answer
The Mario Jump? 2 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
How to fix Jump problem with 2d Platformer Unity demo game? 0 Answers