- Home /
Getting a Vector2 position depending on the rotation of an object
Hey Guys,
so I have a 2D game. I want my character to test, whether an object is too close to it by sending Raycasts to the mouse Position (the direction he will be going). If so then it should not move. My character is a cube with a small cube ontop to illustrate the direction
Now my character can also hang on these white walls, i.g. change rotation. In my code I want to calculate the position from where the rays should fire (I have rays colliding with own collider disabled). So I need to calculate these positions (blue dots) relative to the objects rotation. How do I do that? My approach is to first calculate the spacing. I do that by dividing the "width" of the sprite (which I hardcoded as 0.5f) by the number of rays - 1. I want the last ray to always be on the end so I do not include it. Then I calculate the position as seen in the for-loop. And I do not know how to rewrite it like so, that the position defined by the hard coded values are not in world space, but local space. How do I do that? transform.TransformPoint does not seem to work as well as multiplying by transform.up.
Maybe someone has a suggestions. Here is the code:
private bool ValidateMove()
{
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
bool hitSomething = false;
float spacing = 0.5f / rayCount;
for (int i = 0; i < rayCount - 1; i++)
{
Vector2 position = new Vector2(transform.position.x - 0.25f + spacing * i, transform.position.y - 0.24f);
RaycastHit2D hit = Physics2D.Raycast(position, (mousePosition - position).normalized, maxWallDistance);
if (hit.collider != null)
{
if (hit.collider.gameObject.CompareTag("isEnvironment"))
{
hitSomething = true;
}
}
}
Vector2 positionLast = new Vector2(transform.localPosition.x + 0.25f, transform.position.y - 0.24f);
RaycastHit2D hitLast = Physics2D.Raycast(positionLast, (mousePosition - positionLast).normalized, maxWallDistance);
if (hitLast.collider != null)
{
if (hitLast.collider.gameObject.CompareTag("isEnvironment"))
{
hitSomething = true;
}
}
if (hitSomething)
{
return false;
}
return true;
}
Your answer
Follow this Question
Related Questions
NullReferenceException when using raycast 1 Answer
transform.right not working correctly? 0 Answers
How to make Camera position Independent of its Rotation? 1 Answer
setting transform physics2d issue 0 Answers
Align objects based on child objects 0 Answers