- Home /
Get angle from Object to nearest point of other Object
What I want to do is create a mechanic in my top-down shooter that allows the player to switch which side the gun is held depending on what angle you're colliding against a wall, so you're able to shoot around the corner.
I was easily able to get the gun to move to one side when a trigger infront of the player collides with a wall, but I'm having trouble getting it to switch sides depending on the angle the player's looking at the wall.
I thought of using the player position and object's position to determine the angle that trigger's the player to switch gun positions, maybe using raycast or something. The problem with that is it uses the object's center position, making it so the angle is only ever right if the player is in a specific location against the center of wall, which doesn't work out well.
Here's the script incase it helps.
void Position()
{
//If AIMING
if (Input.GetMouseButton(1))
{
//If holding a weapon
if (activeObject != null)
{
//if NOT colliding against a wall, aim gun forward
if (!forwardHit.colliding)
{
handPos.transform.position = Vector3.MoveTowards(handPos.transform.position, readyPos.transform.position, 0.8f);
}
//otherwise, aim gun to the side of aim position(to shoot around the wall)
else
{
handPos.transform.position = Vector3.MoveTowards(handPos.transform.position, idlePos.transform.position + idlePos.transform.TransformDirection(Vector3.back*(activeObject.transform.localScale.z*4) + idlePos.transform.TransformDirection(Vector3.right*3)), 0.8f);
}
}
}
//if not AIMING, position gun in idle position.
else
{
handPos.transform.position = Vector3.MoveTowards(handPos.transform.position, idlePos.transform.position, 0.8f);
}
//Rotate hand/gun to player's rotation
handPos.transform.rotation = Quaternion.Slerp(handPos.transform.rotation, idlePos.transform.rotation, 0.1f);
}
//Script on Collider
void OnTriggerStay(Collider other)
{
if (other.gameObject.tag == "Wall")
{
colliding = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Wall")
{
colliding = false;
}
}
I haven't coded in the position for the other side yet, since I've yet to figure out how to determine when to switch sides.