- Home /
Question by
SirSmileX · Jun 24, 2018 at 06:40 PM ·
c#physics2d.raycast
RaycastHit2D does not work?
Hey Guys,
so I want my 2D character to be able to dash towards the mouse position when clicking. But it should not do so when the mouse position it sticks to (because it is slimy) is behind the wall or to close to the character (otherwise it would flip into the wall). I have this script that checks whether the wall is far away enough but it does not seem to work
void FixedUpdate ()
{
if (Input.GetMouseButtonDown(0) && canMove)
{
if (!isClicked) {
canMove = false;
Quaternion direction = DirToMousePoint();
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction.eulerAngles);
if (hit.distance >= 0.1)
{
transform.rotation = direction;
transform.eulerAngles = new Vector3(0f, 0f, transform.eulerAngles.z);
rb.AddForce(transform.up * dashSpeed * 50);
}
}
}
}
Quaternion DirToMousePoint()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Quaternion rot = Quaternion.LookRotation(transform.position - mousePosition, Vector3.forward);
return rot;
}
Comment