- Home /
Transform.Position when Play changes
I am facing an issue as follow:
The circle is located circle location before play the game.
when press play it goes to another place as shown here after press play
here is the code I am using, I am pretty sure its a if statement issue:
public class circularmouse : MonoBehaviour {
[SerializeField] float timeCounter = 0;
[SerializeField]bool Direction = false;
[SerializeField] float angularSpeed = 0f;
public Vector3 startPosition;
private void Start()
{
startPosition = transform.position;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
angularSpeed = 4f;
Direction = true;
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
Direction = false;
angularSpeed = 4f;
}
if (Direction) //if direction is true
{
timeCounter += Time.deltaTime * angularSpeed;
float x = Mathf.Cos(timeCounter);
float y = Mathf.Sin(timeCounter);
transform.position = new Vector3(x, y, 0);
}
else
{
timeCounter -= Time.deltaTime * angularSpeed;
float x = Mathf.Cos(timeCounter);
float y = Mathf.Sin(timeCounter);
transform.position = new Vector3(x, y, 0);
}
}
}
Answer by SlowCircuit · Jan 25, 2019 at 09:58 PM
Direction is false by default. The way you have it set up, if Direction is false, it does this: ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
timeCounter -= Time.deltaTime * angularSpeed;
float x = Mathf.Cos(timeCounter);
float y = Mathf.Sin(timeCounter);
transform.position = new Vector3(x, y, 0);
angularSpeed defaults to 0. The Cosign of 0 is 1, The Sin of 0 is 0. Thus, it sets your new position at 1, 0.
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
You need to check if angularSpeed is above 0 before continuing past the input checks. ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
Try adding if (angularSpeed <= 0) return;
before the movement code.
Thank you for your prompt reply.
What I need to know is that, I set the position for the (circle) object to be the same the original place when starting the game, as below:
public Vector3 startPosition;
private void Start()
{
startPosition = transform.position;
}
and that didnt happen