- Home /
My gameobject only moves to the right once and then stops, why?
I am trying to move my gameobject to the right until it reaches its destination (which is just before the edge of the ground platform). Currently my object only moves to the right once (roughly 0.1) and then wont move right any further.
The gameobject starts at (0, 1, 0).
groundSize is the renderer bounds of the ground platform and is using the correct values as I have tested these with public variables.
Below is the code within the script to move the object to the right.
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
if (this.gameObject.transform.position.x >= 0 && this.gameObject.transform.position.x <= ((groundSize.x / 2) * (2 / 3)))
{
transform.Translate(Vector3.right * Time.deltaTime * sideSpeed);
}
if (this.gameObject.transform.position.x >= ((groundSize.x / -2) * (2 / 3)) && this.gameObject.transform.position.x <= 0)
{
transform.Translate(Vector3.right * Time.deltaTime * sideSpeed);
}
Any help is greatly appreciated.
Answer by anaytekstar · Feb 26 at 12:39 PM
So I managed to figure out why it wasn't working, and it was such a simple yet careless mistake.
The calculations carried out on groundSize.x in the conditions were converting to integers as I had written the numbers as 2 and 3, and not 2f and 3f.
Answer by AntiBeta · Feb 25 at 12:05 AM
HI Is your code inside of Update() it's sounds like it is inside of Start()
and you can use the code like that :
private void Update()
{
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
if ((tf.position.x >= 0 && tf.position.x <= groundSize.x / 3) ||
( tf.position.x < 0) && tf.position.x >= ((groundSize.x / -3)) )
{
tf.Translate(Vector3.right * Time.deltaTime * sideSpeed);
}
}
}
GL ༼ つ ◕_◕ ༽つ
Answer by anaytekstar · Feb 25 at 12:18 AM
Hi, thanks for the reply @AntiBeta.
My code is in the update() section.
The only thing in start() is
ground = GameObject.Find("Ground");
groundSize = ground.GetComponent<Renderer>().bounds.size;
I didnt think about putting both statements together so I'll definitely do that as it makes more sense, but it still doesn't make sense to me why it doesn't work.
Well I tried the code by myself and it worked. you can check groundSize because I used it like Vector3(100f,100f,100f)
Ok, I'll try again and see what happens. Thanks for all the help :)