In Unity, I have an aiming reticule that moves in an arc above the player when either left or right arrows are held.
Based on this reticule, when space is pressed, I move the last position in the line renderer based on that angle. If the length of all positions in the line renderer is more than a certain distance, I place a point to track the position. This happens each time I press space and the idea is that all points will form an arc.
However, something must be wrong with my maths. As you can see in the screenshot, sometimes the point will not be on the arc and it creates a new arc with a smaller radius. This seems to happen if I fire while not holding left or right, so it must be something to do with the crosshairAngle
.
The green dots are placed once the line reaches a max length, the red dot is the crosshair.
void Update() {
HandleAiming();
HandleRopeOut();
}
private void HandleAiming() {
float x = crosshair.transform.position.x;
float y = crosshair.transform.position.y;
float speed = 2f;
if (Input.GetKey(KeyCode.LeftArrow)) {
x = transform.position.x + Mathf.Cos(crosshairAngle) * arcRadius;
y = transform.position.y + Mathf.Sin(crosshairAngle) * arcRadius;
crosshairAngle += speed * Time.deltaTime;
if (crosshairAngle > Mathf.PI) {
crosshairAngle = Mathf.PI;
}
}
if (Input.GetKey(KeyCode.RightArrow)) {
x = transform.position.x + Mathf.Cos(crosshairAngle) * arcRadius;
y = transform.position.y + Mathf.Sin(crosshairAngle) * arcRadius;
crosshairAngle -= speed * Time.deltaTime;
if (crosshairAngle < 0) {
crosshairAngle = 0;
}
}
crosshair.transform.localPosition = new Vector3(x, y, 0) - transform.position;
ropeAnchor.localPosition = crosshair.transform.localPosition;
}
private void HandleRopeOut() {
Vector3 initialPosition = rope.GetPosition(1);
float x = initialPosition.x + Mathf.Cos(crosshairAngle) * arcRadius;
float y = initialPosition.y + Mathf.Sin(crosshairAngle) * arcRadius;
float currentLength = Vector3.Distance(new Vector3(x, y), rope.GetPosition(0));
// Set the last position of the line renderer to animate it moving
rope.SetPosition(1, new Vector3(x, y, 0));
if (currentLength >= 12f) {
// Debug to add a point to the position to map the arc
GameObject point = Instantiate(arcPoint);
point.transform.parent = transform;
point.transform.localPosition = new Vector2(x, y);
HandleRopeReset();
}
}