简体   繁体   中英

Unity 3D C# camera - nudging/moving camera in direction of mouse or joystick

I am making a top down shooter with a 45 degree camera angle. In my scene I have the camera childed to the player to follow the player. I have seen in a couple of games like "Secret Ponchos" where the camera slightly floats to the direction the player is aiming. It's subtle but adds polish.

I have tried a couple of different ways but don't know how to get the Vector for the Lerp. Is there a way I can base the nudging based on mouseMovement? If so How?

To get the position to use for the Lerp of your camera control, you just need to figure out the direction you want the camera to nudge in and add that to the player's position.

One option is to use transform.forward to use the direction your player is facing however this requires you to rotate your player character.

//Assign the player's transform here
public Transform Target;

Vector3 GetNudgeDirection () {
     return Target.forward;
}

Another method would be to get the direction of the mouse relative to the player.

public Transform Target;

Vector3 GetNudgeDirection () {
   //Get the position of the mouse
   Vector3 mousePos = Input.mousePosition;
   mousePos.z = -Camera.main.transform.position.z;
   Vector2 inputPos = Camera.main.ScreenToWorldPoint(mousePos);
   //returns direction from the player to the mouse pos.
   return (inputPos - (Vector2)Target.position).normalized;
}

You would then add the nudge direction to the target's position to get where your camera should aim at.

//This field determines how far to nudge
private float nudgeDistance = 2f;

Vector3 GetTargetPosition () {
     return Target.position + (GetNudgeDirection() * nudgeDistance);
}

Keep in mind the target position is where your camera should look, not where it should move to! So when you are actually moving your camera, add an offset to the target position so it maintains its distance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM