- Home /
The question is answered, right answer was accepted
3rd person 3D aiming
Hello.
Currently I'm trying to make an aiming system for a 3D, 3rd person game. My goal is to have the character aim the attack (a projectile, in this case) in a direction corresponding to the mouse position relative to the character's own position.
Example: if the mouse pointer is above and to the left of the character, I want the attack to be aimed forward, but with an upward and a leftward angle; this angle should increase the further the mouse pointer is relative to the character.
Unfortunately, I can't quite get this system to work. What am I doing wrong?
public override void Aim(float range, Camera mainCamera, Transform firingPoint, LayerMask terrainMask)
{
Ray ray = mainCamera.ViewportPointToRay(Input.mousePosition);
float targetRayDistance = Vector3.Distance(mainCamera.transform.position, firingPoint.position) / Mathf.Cos(Vector3.Angle(mainCamera.transform.forward, -firingPoint.forward)) + range; //this takes into the account the angle the camera is at relative to the character, and compensates
if (Physics.Raycast(ray, targetRayDistance, terrainMask, QueryTriggerInteraction.Ignore))
{
firingPoint.rotation = Quaternion.LookRotation(ray.GetPoint(targetRayDistance), firingPoint.up); //if the Raycast collides with terrain, that means the projectile will too; I don't want that; therefore the projectile will be aimed horizontally instead
}
else
{
firingPoint.rotation = Quaternion.LookRotation(ray.GetPoint(targetRayDistance));
}
}
Answer by Fa6ex · Jun 21, 2019 at 04:20 PM
Alright, figured it out after a bit more searching. The answer is here https://stackoverflow.com/questions/29689617/mouse-based-aiming-unity3d but I adapted it slightly to fit what I was trying to do.
Vector3 GetMousePositionInPlaneOfLauncher () {
Plane p = new Plane(mainCamera.transform.forward, firingPoint.position);
Ray r = mainCamera.ScreenPointToRay(Input.mousePosition);
float d;
if(p.Raycast(r, out d)) {
Vector3 v = r.GetPoint(d);
return v;
}
throw new UnityException("Mouse position ray not intersecting launcher plane");
}
firingPoint.LookAt(GetMousePositionInPlaneOfLauncher());
Follow this Question
Related Questions
Player Chest rotates always in the same direction 0 Answers
Making an object follow the mouse in 3D world 0 Answers
Rotation of Object on single axis in direction of the mouse position 0 Answers
How do I make sure that a ray ALWAYS points straight down? 2 Answers
RayCasting shows wrong point 1 Answer