- Home /
I'm trying to get an object to move using javascript however it won't move, can someone help?
this is the code I used
var gravity = 9;
var movSpeed = 9;
var isMoving = false;
function Start () {
}
function Update () {
if(Input.GetButton("Horizontal"))
{
isMoving = true;
}
while(isMoving)
{
if(Input.GetButton("Horizontal"))
{
transform.position.x = movSpeed;
}
if(Input.GetButtonUp("Horizontal"))
{
isMoving = false;
}
}
}
if anyone could help I would be really greatful
Answer by bobisgod234 · May 09, 2017 at 04:07 AM
Firstly, try to make sure your code is tabbed correctly, as its very hard to see whats in what condition:
function Update () {
if(Input.GetButton("Horizontal"))
{
isMoving = true;
}
while(isMoving)
{
if(Input.GetButton("Horizontal"))
{
transform.position.x = movSpeed;
}
if(Input.GetButtonUp("Horizontal"))
{
isMoving = false;
}
}
}
The while loop is unnecessary, update is called repeatedly once a frame already. Since we want to only change the position when Input.GetButton("Horizontal") is true, we can remove most of the rest of the code too.
function Update () {
if(Input.GetButton("Horizontal"))
{
transform.position.x = movSpeed;
}
}
Now here, we are setting the x position of the transform to movSpeed, so each frame the position of the object won't actually change. We want to add movSpeed to the x position, using += instead of =.
function Update () {
if(Input.GetButton("Horizontal"))
{
transform.position.x += movSpeed;
}
}
Your answer
Follow this Question
Related Questions
Alternative to using transform.translate and transform.position for moving objects exact values? 1 Answer
Cant Get Character To Move 1 Answer
Translating Javascript code into C# Code 2 Answers
Setting Scroll View Width GUILayout 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers