- Home /
UI object move?
I have a red square image and I want to move it like in the image below 1 - 3.
I wrote this script:
RectTransform rectTransform;
void Start () {
rectTransform = GetComponent<RectTransform>();
}
void Update () {
Vector2 aPos = rectTransform.position;
aPos.x = aPos.x * Time.deltaTime;
rectTransform.position = aPos;
}
I attached this script to the red square image. I also want to check if it's greater than X position and start the move again from start. When I press play the red square looks like in the image 4. It's not moving. I also tried anchoredPosition and localposition. It's not working. Why?
Answer by Defetysta · Nov 27, 2018 at 10:29 AM
You are not changing the value that is being assigned to transform.position. Each frame you are taking aPos.x and multiply it by Time.deltaTime and assigning it back to transform.position. Try something like this:
aPos = transform.position;
aPos.y = aPos.z = 0;
aPos.x = movementSpeed * Time.deltaTime;
transform.position += aPos;
Answer by Hellium · Nov 27, 2018 at 10:32 AM
Try the following:
public float HorizontalSpeed = 1 ;
public float MaxHorizontalPosition = 200 ;
public float MinHorizontalPosition = -200 ;
// Please, name correctly your variables.
// Yourself, in 3 months will be grateful
private RectTransform rectTransform;
void Start ()
{
rectTransform = GetComponent<RectTransform>();
}
void Update ()
{
Vector2 position = rectTransform.anchoredPosition;
position.x += HorizontalSpeed * Time.deltaTime;
if( position.x > MaxHorizontalPosition )
position.x = MinHorizontalPosition ;
rectTransform.anchoredPosition = position;
}
Your answer
Follow this Question
Related Questions
UI Image size 1 Answer
How to see what the UI canvas will look like in the final build? 0 Answers
Images order inside Canvas 1 Answer
Shoot accuracy bar 1 Answer