- Home /
How do add force to the left (x-axis)
I am very new to unity, and I created a very simple 2d "game" in which a ball falls from a height and lands on platforms. I was successfully able to script the ball in Javascript to move right upon user input. For some reason though, I cannot let the user add force to the left no matter what I try. I know this must be painfully simple and stupid, so many thanks to whoever deigns to answer this. The code is below
Original without force to the left; works perfectly:
#pragma strict
function FixedUpdate () {
if (Input.GetKey ("right"))
rigidbody2D.AddForce(Vector2.right * 10);
}
My failed attempt to implement left movement:
#pragma strict
function FixedUpdate () {
if (Input.GetKey ("right"))
rigidbody2D.AddForce(Vector2.right * 10);
}
function FixedUpdate () {
if (Input.GetKey ("left"))
rigidbody2D.AddForce(Vector2.(0,-1) * 10);
}
Thank you again
I also now notice that the "left" coordinates are misplaced. Though these are now fixed, I still cannot run the program.
function FixedUpdate () {
if (Input.Get$$anonymous$$ey ("left"))
{
rigidbody2D.AddForce(Vector2.left * 10);
}
}
Why don't you do it in one function FixedUpdate()
Answer by JacobHockey13 · Mar 12, 2014 at 03:52 AM
Thank you for the answer. This helped along with removing the period before the coordinates
Answer by JacobHockey13 · Mar 12, 2014 at 03:52 AM
I fixed my code to no longer have a fixed my code to no longer contain a period, and used just a simple Update as the new function. However, if I also wanted to have this as a FixedUpdate what would I do? Here is the working code. #pragma strict
function FixedUpdate () {
if (Input.GetKey ("right"))
rigidbody2D.AddForce(Vector2.right * 10);
}
function Update () {
if (Input.GetKey ("left"))
rigidbody2D.AddForce(Vector2(-1,0) * 10);
}
Thank you highpockets for the answer. I also do not know how to mark your answer as correct (embarrassing), so how would I do that?
If you want to ask more questions just do it with the 'add new comment' button on the lower right of the answer that I put, do not post a new answer. To mark my answer as correct click the tick mark on the top left of my answer. To place everything in FixedUpdate(), do the following:
function FixedUpdate ()
{
if (Input.Get$$anonymous$$ey ("right"))
{
rigidbody2D.AddForce(Vector2.right * 10);
}
if (Input.Get$$anonymous$$ey ("left"))
{
rigidbody2D.AddForce(Vector2(-1,0) * 10);
}
}