- Home /
2D jump with Raycast
Hello everyone, I'm new to Unity and programming and I'm doing my first 2D platformer.
I'm writing my own script for the player to move and I've got a problem with the raycast. I've got two cubes: the floor that has got a box collider 2D, and the player that's got a box collider 2D and a rigidbody 2D.
What I want to do is to detect the floor using the raycast and make the player able to jump then. The problem is the raycast seems to be active all the time so it actually doesn't change anything. When I delete the "Input.GetKeyDown(KeyCode.Space)" then the character just flies away. Here's the whole code:
var speed : float = 10F;
var jumpSpeed : float = 10F;
function Update() {
transform.Translate(Input.GetAxis("Horizontal") * speed * Time.deltaTime, 0, 0, Space.World);
var hit : RaycastHit2D = Physics2D.Raycast(transform.position, -Vector2.up);
if((hit != null) && (Input.GetKeyDown(KeyCode.Space))) {
Jump();
}
}
function Jump() {
rigidbody2D.velocity = new Vector2(0, jumpSpeed);
}
I was looking for the answer for a very long time and checked a lot of possibilities - nothing works.
Sorry for my English if I made any mistakes
Answer by koray1396 · Apr 22, 2014 at 04:28 PM
Try this;
float someValue = 0.1f;
Physics2D.Raycast(transform.position, -Vector2.up, someValue);
you can set a maximum distance of the ray to check if the player is on ground.
Hmm, nothing changed, the ray's active all the time. Any other ideas?
oops, this also;
public Layer$$anonymous$$ask GroundLayer;
you should select the layer of ground only, it is possibly detecting player itself.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Questions about movement on uneven/slopped terrain and terrain coliders 0 Answers
2D Platform Player moving instantly from upper platform to lower, only when moving left 0 Answers
How to prevent jitter with movement over curved slopes 0 Answers
Help setting maxAceleration 0 Answers