- Home /
How to change transform.position.x to go backwards at specific instance?
Hi,
I'm having some trouble with moving my character. I'm trying to get it to go in the negative x direction when the character passes a certain x position. Any help?
public class Movement : MonoBehaviour {
public float moveSpeed;
// Use this for initialization
void Start () {
moveSpeed = 0.8f;
}
// Update is called once per frame
void Update () {
transform.position += new Vector3(.0001f, 0, 0);
if ((transform.position.x) > 0.005 && transform.position.x < .01) {
transform.position -= new Vector3(.0001f, 0, 0);
}
}
}
Answer by tmalhassan · Sep 26, 2017 at 03:46 AM
Hello @miwwes.
The problem with your code is that you're telling the object to move right and after that you're immediately telling it to go left. That's is why it seems stuck at 0.0049. You can fix this by manipulating the situation and changing the if statement.
Try changing your code to something like this:
public float moveSpeed;
private bool moveRight = true;
void Start()
{
moveSpeed = 0.8f;
}
void Update()
{
if (moveRight == true)
{
transform.position += new Vector3(0.0001f, 0, 0);
if ((transform.position.x) >= 0.01f)
{
moveRight = false;
}
}
else
{
transform.position -= new Vector3(0.0001f, 0, 0);
if ((transform.position.x) <= 0)
{
moveRight = true;
}
}
}
Let me know how it goes and all the best :)
$$anonymous$$y object got stuck at 0.4999 and that happened before as well on my code. Any thoughts?
It worked the very first time I implemented it! However, after that, it got stuck again. Between 0.00499 and 0.005. Even if I were to change it to make it change at a later x position it would be get stuck. Thank you so much for helping me!
Oh, so you want it to keep on moving back and forth?
Yes, but with that code, it moved right, then moved left on the first run. After the first run, it went right and stopped. Regardless, It should be going right then left after every time i first run the program right?
Answer by irfan-ayub · Sep 26, 2017 at 05:55 AM
If you want to access a particular axis in any transform component you can always reference it separately.
you can do it like this:
public float moveSpeed;
// Use this for initialization
void Start () {
moveSpeed = 0.8f;
}
// Update is called once per frame
void Update () {
transform.position.x += 0.0001f;
if ((transform.position.x) > 0.005f && transform.position.x < 0.01f) {
transform.position.x -= 0.0001f;
}
}
I tried this and got an error telling me I could not modify transform.position's return value
Your answer
Follow this Question
Related Questions
Why is my y-axis bugging? 1 Answer
How do I change one value of a vector? 2 Answers
Nav Mesh and transform.position failure! 0 Answers
Move camera when mouse is near the edges of the screen 1 Answer