- Home /
Can someone review a short script and tell me where I've gone wrong? [JavaScript]
I have began coding a controller for a 2D game and I am having a few issues. Could anyone help me out please!
Code
#pragma strict
var moveUp : KeyCode;
var moveDown : KeyCode;
var moveRight : KeyCode;
var moveLeft : KeyCode;
var speed : float = 10;
var jumpHeight = 8;
function Update ()
{
if (Input.GetKey(moveUp) && isFalling == false)
{
rigidbody2D.velocity.y = jumpHeight;
}
isFalling = true;
else if (Input.GetKey(moveDown))
{
rigidbody2D.velocity.y = speed *-1;
}
else if (Input.GetKey(moveRight))
{
rigidbody2D.velocity.x = speed;
}
else if (Input.GetKey(moveLeft))
{
rigidbody2D.velocity.x = speed *-1;
}
else
{
rigidbody2D.velocity.y = 0;
rigidbody2D.velocity.x = 0;
}
}
I have fixed the code, I amended these __> { (Would love to know what they're called!)
I also added a private variable. I have no errors but the whole controller works weirdly! The player slowly falls depending on if your using left and right or not. You can infinity jump too!
Does anyone know how to probably configure jump to the w key?
$$anonymous$$y Code
#pragma strict
var moveUp : $$anonymous$$eyCode;
var moveDown : $$anonymous$$eyCode;
var moveRight : $$anonymous$$eyCode;
var moveLeft : $$anonymous$$eyCode;
var speed : float = 10;
var jumpHeight = 8;
private var isFalling = false;
function Update ()
{
if (Input.Get$$anonymous$$ey(moveUp) && isFalling == false)
{
rigidbody2D.velocity.y = jumpHeight;
}
if (Input.Get$$anonymous$$ey(moveUp) && isFalling == true)
{
rigidbody2D.velocity.y = 0;
}
else if (Input.Get$$anonymous$$ey(moveDown))
{
rigidbody2D.velocity.y = speed *-1;
}
else if (Input.Get$$anonymous$$ey(moveRight))
{
rigidbody2D.velocity.x = speed;
}
else if (Input.Get$$anonymous$$ey(moveLeft))
{
rigidbody2D.velocity.x = speed *-1;
}
else
{
rigidbody2D.velocity.y = 0;
rigidbody2D.velocity.x = 0;
}
}
Thanks again
you should set isFalling to false when you land and set it to false when you jump.
function OnCollisonStay2D( collision2D :Collision2D)
{
if(collision2D.comparetag("Ground"))
isFalling = false;
}
Hi, I am trying to implement this within my code right now. The problem is I've never seen these pieces of code before and I'm not sure where they go!
Also when you jump wouldn't isFalling be true? Could you show me how the code should be please?
Thanks. I was just wondering if it had a different name within the coding world!
Answer by gospod velebrz · Dec 03, 2013 at 05:38 PM
check the script reference. It is one of the biggest assets of the Unity engine, and it quickly improves your understanding on basic scripting stuff
http://docs.unity3d.com/Documentation/ScriptReference/30_search.html?q=on+collision+stay
Your answer
Follow this Question
Related Questions
Need Help Understanding Script! (Javascript) 1 Answer
OnMouseEnter Error 1 Answer
It is not possible to invoke an expression of type 'UnityEngine.GameObject'? 1 Answer
Error in distance coding 1 Answer
Destroy Other 2 Answers