- Home /
Rotate Sprite along shape?
Hi,
I'm trying to have a sprite orient itself along the sides of a circuloid; an octogon, for example. When I move the sprite it orients itself very well but only on one side of the sprites being raycasted. The left half is being raycasted but not the right for some reason. I've attached an image illustrating my issue.
Here is the code i'm currently using:
void Raycasting()
{
//raycast from rectangle to selected shape/body
RaycastHit2D hit
= Physics2D.Raycast(transform.position,
body.position,
Mathf.Infinity,
1 << LayerMask.NameToLayer("Ground"));
//if hit != null...
if(hit.collider)
{
//Rotate sprite according to normal
float angle = Mathf.Atan2(hit.normal.y, hit.normal.x) * Mathf.Rad2Deg;
Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * rotationSpeed);
//set position of red dot representing hit point
contact.position = hit.point;
//update cached hitPoint v3
hitPoint = hit.point;
}
}
I discovered the issue has something to do with the position of the sprite being raycasted. $$anonymous$$aybe the direction vector.
Detecting the x position of the raycast origin relative to the raycasted object, then flipping that objects position almost solves the issue. I'm not satisfied with this inconsistent and a hacky temp solution. Does anyone have a better solution; know why this happens?
Vector3 bodyPosition;
if(transform.position.x < body.position.x)
bodyPosition = body.position;
else
bodyPosition = -body.position;
//raycast from rectangle to selected shape/body
RaycastHit2D hit
= Physics2D.Raycast(transform.position,
bodyPosition,
$$anonymous$$athf.Infinity,
1 << Layer$$anonymous$$ask.NameToLayer("Ground"));