How can I translate my game object from a certain coordinate to the negative values of the same coordinate?
I want to create a game similar to Loop Mania on the iPhone App Store. For this, I am calling upon Vector2 and using trigonometric functions which move my object in a circle. However, I want the object to translate to the negative values of the coordinates in a straight line when the left button on a mouse is clicked. For example, if my object is at (2, 3) at a certain point in time, I want it to translate in a straight line to (-2, -3). This is my code so far. I appreciate any and all help.
private float x, y, a, b;
private float timeCounter;
private float speed;
private float slope;
private Vector2 targetPosition;
private void Start ()
{
x = 2.95f;
y = 0f;
timeCounter = 0f;
speed = 2.5f;
}
//Updates x and y coordinates of the circle
private void Update()
{
timeCounter += Time.deltaTime * speed;
x = Mathf.Cos(timeCounter) * 2.95f;
y = Mathf.Sin(timeCounter) * 2.95f;
a = -x;
b = -y;
transform.position = new Vector2(x, y);
targetPosition = new Vector2(a, b);
translateAcross();
}
private void translateAcross()
{
if(Input.GetMouseButtonDown(0))
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, timeCounter);
}
}
Answer by Mindmapfreak · Jun 26, 2016 at 11:43 AM
It is probably easier to use Unity's built-in functions:
private float angularSpeed;
private float speed;
private Vector2 targetPosition;
private void Start()
{
this.angularSpeed = 100.0f;
this.speed = 10.0f;
this.transform.position = new Vector2(0, 2.95f);
this.targetPosition = this.transform.position;
}
//Updates x and y coordinates of the circle
private void Update()
{
if (Vector2.Distance(transform.position, targetPosition) < 0.0001f)
{
this.transform.RotateAround(Vector2.zero, Vector3.forward, Time.deltaTime * this.angularSpeed);
this.targetPosition = this.transform.position;
}
else
{
this.transform.position = Vector2.MoveTowards(this.transform.position, this.targetPosition, Time.deltaTime * this.speed);
}
if (Input.GetMouseButtonDown(0))
{
this.targetPosition = -this.transform.position;
}
}
Some additional notes:
There is already a built-in variable that does what you are doing with timeCounter, it is Time.time (except when you want to save the time for a specific object)
Input.GetMouseButtonDown only gets called once in the frame in which the mouse button is pressed (which was part of your problem)
I looked through the documentation page but didn't catch that. Thank you very much! I would reward you with points if I had any. I just joined recently.