Angle Between Two Vector2

Hi,

I’m trying to work out the angle between…

  • Where the user has touched and…
  • The centre of the game object that was touched

I have the vector2 fine of what was touched…I think I have the centre of the game object that was touched. I can’t seem to work out the math (never been good at trig etc).

		if (Input.GetMouseButtonDown (0)) {
			Vector2 pos = new Vector2 (Input.mousePosition.x, Input.mousePosition.y);
			RaycastHit2D hitInfo = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (pos), Vector2.zero);
			if (hitInfo && hitInfo.collider.gameObject == gameObject) {
				switch (hitInfo.transform.gameObject.tag) {
				case "Shape":

					float ang = Vector2.Angle (pos, new Vector2 (Camera.main.WorldToScreenPoint (hitInfo.collider.gameObject.transform.position).x, Camera.main.WorldToScreenPoint (hitInfo.collider.gameObject.transform.position).y + 0.5f));
					Vector3 cross = Vector3.Cross (pos, Camera.main.WorldToScreenPoint (hitInfo.collider.gameObject.transform.position));

					Debug.Log (ang);
					break;
				}
			}
		
		}

Above is what I have so far. The aim is to work out how far from the left of the GameObject the user has pressed, I could only think of using the Vector2.Angle function but if someone has any other ideas it would be great.

Thanks…

I don’t think the angle help you with “how far from the left”, but for this specific angle you are looking for you can do:

Vector3 pos = Camera.main.WorldToScreenPoint(hitInfo.transform.position);
pos = Input.mousePosition - pos;
float angle = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg;

This angle is between Vector3.right and the vector formed by these two point. I’m not sure what you are looking for, but you may need to reverse the subtraction on line 2 to reverse the vector.