Problems with vector3 in world / local space
Im trying to make a 2d game in which you can move the character using wasd and the character is always looking at the mouse. The next thing i want to make is a 2d cone shaped raycast in the direction the character is looking. The code i have right now is this: (Dont mind the debug.line, this is just to visualise the rays for later)
//variables for rotating object to mouse position
var mousePosition = Input.mousePosition;
var screenPoint = Camera.main.WorldToScreenPoint(transform.localPosition);
var offset = new Vector2(mousePosition.x - screenPoint.x, mousePosition.y - screenPoint.y);
var angle = Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, angle);
//Cone 60 degrees, 30 degrees to top, 30 degrees to bottom
for (int i = 0; i < 30; i = i + 2)
{
var rad = i * Mathf.PI / 180;
difference = (Mathf.Tan(rad) * 5);
Vector3 directionUp = new Vector3(transform.position.x + 5, transform.position.y + difference, 0.0f);
Vector3 directionDown = new Vector3(transform.position.x + 5, transform.position.y - difference, 0.0f);
Debug.DrawLine(transform.position, directionUp, Color.green);
Debug.DrawLine(transform.position, directionDown, Color.green);
}
However now the debug lines are always facing the world axis of transform.position.x + 5, so it is not facing the direction it is looking. I was hoping that using transform.position.x + 5 would use the local x/ y axis of the object with rotation in mind but it doesnt seem to work like that. Im guessing it has something to do with local/ world space but no idea how to fix this. Any tips for fixing this?
Answer by TreyH · May 14, 2019 at 10:14 AM
This is going to give you a junk value:
var screenPoint = Camera.main.WorldToScreenPoint(transform.localPosition);
Local position is only for checking / setting an object's position with respect to its direct parent. You aren't going to have a meaningful use of that outside of those cases, especially not with something as absolute as something's position on screen.
Use the object's absolute world position instead:
var screenPoint = Camera.main.WorldToScreenPoint(transform.position);
I didn't look through the rest of your work, but see if that resolves your issue.
Your answer
Follow this Question
Related Questions
Unity2d worldspace / local space vector 3 help needed 0 Answers
Trying to Generate Different Random Values for Position of Game Object Instances [C#] 1 Answer
Unity Android build multiplying decimal numbers by 10 for an unknown reason 0 Answers