- Home /
Unity2d rotation, transform.position and raycasting question
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. Any tips for fixing this?
Your answer
![](https://koobas.hobune.stream/wayback/20220612201338im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Object doesn't move 2 Answers
How to use a Vector3.MoveTowards and the resulting position as an input for a normalised BlendTree 0 Answers
How to teleport gameobject (instantly change transform.position) 3 Answers
Transform Position 1 Answer
Get an Object to move to a Position for a Fixed time 2 Answers