Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Move camera a bit depending on the mouse position

Discussion in 'Scripting' started by VisualTech48, May 12, 2016.

  1. VisualTech48

    VisualTech48

    Joined:
    Aug 23, 2013
    Posts:
    247
    Hi folks!

    I want to make my camera move a bit, where the mouse is in the screen like this, but not doing it soon well to be honest. If anyone could help it would mean a lot!

    Sorry for bad paint job:
    Test_Mouse.png
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    You want the camera to focus on a midpoint between the player and the mouse position.

    focusPoint = (player.position + mousePosition) / 2;

    I'm willing to help more, but I'd need more info (is the project 2D or 3D, do you need help getting the mouse position, etc.)
     
  3. VisualTech48

    VisualTech48

    Joined:
    Aug 23, 2013
    Posts:
    247
    Its in 3d space and I want the object to be just like you said, in the mid point of those 2, The Mouse and the Player.
     
  4. VisualTech48

    VisualTech48

    Joined:
    Aug 23, 2013
    Posts:
    247
    Also I do not want the camera, to ever escape from the player
     
  5. Dreamteck

    Dreamteck

    Joined:
    Feb 12, 2015
    Posts:
    336
    Maybe you can calculate distance between the mouse and the camera and then use it as a multiplier to restrict the movement of the camera.

    Try this in a monobehaviour (untested):
    Code (CSharp):
    1.     public Transform cam;
    2.     public Transform target1;
    3.     public Transform target2;
    4.     public float height = 2f;
    5.     public float maxOffset = 5f;
    6.  
    7.     void Update () {
    8.         float dist = Vector3.Distance(target1.position, target2.position);
    9.         float distPercent = Mathf.Clamp01(dist / maxOffset);
    10.         Vector3 delta = (target2.position - target1.position);
    11.         Vector3 maxDelta = Vector3.Normalize(delta) * maxOffset;
    12.         Vector3 finalDelta = Vector3.Lerp(delta, maxDelta, distPercent);
    13.         cam.position = target1.position + finalDelta*0.5f + Vector3.up * height;
    14.     }
    Target1 would be the player, Target2 would be the mouse. Height defines the height of the camera. Use maxOffset to restrict the camera movement so target1 would never be out of sight.
     
    VisualTech48 likes this.
  6. VisualTech48

    VisualTech48

    Joined:
    Aug 23, 2013
    Posts:
    247
    Sorry for a late reply was out a bit.

    I'll give it a shoot, and tell you if it works. Thanks a bunch!