Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by ThePinkPanzer · Feb 21, 2017 at 02:34 PM · c#cameramovementnewbie

Making the camera follow the mouse but stay near the player?

I have my player running around well and the camera works, but I don't want my camera attached square on the player. I'm making an isometricish dungeon crawler and wanted the camera to more or less follow the player and for the player to face the mouse pointer, but for the camera to drift to wherever the mouse is currently.

In other words, the camera follows the mouse, but there is a 'boundary' around the player so if he starts moving it'll tag along. This will probably conflict with my current camera, as it relies on the player facing where the camera is pointing on a Vector3.

My current movement file:

     using System.Collections;
     using System.Collections.Generic;
     using UnityEngine;
     
     [DisallowMultipleComponent]
     [RequireComponent(typeof(Animator))]
     [RequireComponent(typeof(Rigidbody))]
     [RequireComponent(typeof(CapsuleCollider))]
     
     public class Movement : MonoBehaviour {
         Animator anim;
     
         private Camera mainCamera;
     
         bool isWalking = false;
     
         const float WALK_SPEED = .25f;
     
         void Start ()
         {
             mainCamera = FindObjectOfType<Camera>();
         }
     
         void Awake()
         {
             anim = GetComponent<Animator>();
         }
     
         void Update()
         {
     
             Turning();
             Walking();
             Move();
             Jump();
     
             //Player look
             Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
             Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
             float rayLength;
     
             if (groundPlane.Raycast(cameraRay, out rayLength))
             {
                 Vector3 pointToLook = cameraRay.GetPoint(rayLength);
                 Debug.DrawLine(cameraRay.origin, pointToLook, Color.blue);
     
                 transform.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));
             }
         }
     
         void Turning()
         {
             anim.SetFloat("Turn", Input.GetAxis("Horizontal"));
         }
     
         void Walking()
         {
             if (Input.GetKeyDown(KeyCode.LeftShift)) {
                 isWalking = !isWalking;
                 anim.SetBool("Walk", isWalking);
             }
         }
     
     
         void Move()
         {
             /*
              *
              */
             if (anim.GetBool("Walk"))
             {
                 anim.SetFloat("MoveZ", Mathf.Clamp(Input.GetAxis("MoveZ"), -WALK_SPEED, WALK_SPEED));
                 anim.SetFloat("MoveX", Mathf.Clamp(Input.GetAxis("MoveX"), -WALK_SPEED, WALK_SPEED));
             }
             else
             {
                 anim.SetFloat("MoveZ", Input.GetAxis("MoveZ"));
                 anim.SetFloat("MoveX", Input.GetAxis("MoveX"));
             }
         }
     
         void Jump()
         {
             if (Input.GetKeyDown(KeyCode.Space))
                 anim.SetTrigger("Jump");
         }
     }

My current camera file:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class SmoothCamera : MonoBehaviour
 {
 
     public Transform lookAt;
 
     private bool smooth = true;
     private float smoothSpeed = 0.125f;
     private Vector3 offset = new Vector3(0, 10, -10);
 
     private void LateUpdate()
     {
         Vector3 desiredPosition = lookAt.transform.position + offset;
 
         if (smooth)
         {
             transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
         }
 
         else {
             transform.position = desiredPosition;
         }
     }
 }

I'm still (obviously) pretty new so excuse me if this is a dumb question.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by MarshallN · Feb 21, 2017 at 03:54 PM

So it looks to me like all you need to do is find a different offset value - how about raycasting from the camera to the mouse point (using Camera.ScreenPointToRay(Input.mousePosition)) and then changing offset by some portion of the distance between the lookAt.position and the raycast position?

So something like

 private Vector3 defaultOffset;
 private Camera camera;
 private Vector3 offsetForOffset;
 private float maxDistance;
 private float scaleFactor;
 
 void Start()
 {
     defaultOffset = new Vector3(0,10,-10);
     scaleFactor = 0.5f; //This is to make the camera not go all the way to the mouse cursor position, tweak it until it feels right.
     maxDistance = 3.0f; //This limits how far the camera can go from the player, tweak it until it feels right.
 }
 
 void LateUpdate()
 {
     RaycastHit hit;
     Ray ray = camera.ScreenPointToRay(Input.mousePosition);
     
     if (Physics.Raycast(ray, out hit)) {
         offsetForOffset = (hit.point - lookAt.position) * scaleFactor;
     }
     else
         offsetForOffset = Vector3.zero; // This makes it so that if the camera raycast doesn't hit, we go to directly over the player.
     if(offsetForOffset.magnitude > maxDistance)
     {
         offsetForOffset.Normalize(); // Make the vector3 have a magnitude of 1
         offsetForOffset = offsetForOffset * maxDistance;
     }
     offset = defaultOffset + offsetForOffset;
     
     Vector3 desiredPosition = lookAt.transform.position + offset;
 
     if (smooth)
     {
         transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
     }
 }
     

Lemme know how that works for you?

Comment
Add comment · Show 6 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ThePinkPanzer · Feb 21, 2017 at 07:36 PM 0
Share

I'm 100% sure I'm just too new to understand this but I'm getting al ot of errors for a lot of variables 'not working in the current context'. IE: smooth, smoothSpeed, offset, lookAt.

Otherwise, thank you for the answer.

avatar image MarshallN ThePinkPanzer · Feb 21, 2017 at 07:39 PM 0
Share

Oh - my script wasn't complete, it was to be added to your SmoothCamera script. I'll combine them for you real quick, sorry about that!

  using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  
  public class SmoothCamera : $$anonymous$$onoBehaviour
 {
     private Vector3 defaultOffset;
     private Camera camera;
     private Vector3 offsetForOffset;
     private float maxDistance;
     private float scaleFactor;
     public Transform lookAt;
 
     private bool smooth = true;
     private float smoothSpeed = 0.125f;
     private Vector3 offset = new Vector3(0, 10, -10);
 
     void Start()
     {
         defaultOffset = new Vector3(0, 10, -10);
         scaleFactor = 0.5f; //This is to make the camera not go all the way to the mouse cursor position, tweak it until it feels right.
         maxDistance = 3.0f; //This limits how far the camera can go from the player, tweak it until it feels right.
     }
 
 
 
     void LateUpdate()
     {
         RaycastHit hit;
         Ray ray = camera.ScreenPointToRay(Input.mousePosition);
 
         if (Physics.Raycast(ray, out hit))
         {
             offsetForOffset = (hit.point - lookAt.position) * scaleFactor;
         }
         else
             offsetForOffset = Vector3.zero; // This makes it so that if the camera raycast doesn't hit, we go to directly over the player.
         if (offsetForOffset.magnitude > maxDistance)
         {
             offsetForOffset.Normalize(); // $$anonymous$$ake the vector3 have a magnitude of 1
             offsetForOffset = offsetForOffset * maxDistance;
         }
         offset = defaultOffset + offsetForOffset;
 
         Vector3 desiredPosition = lookAt.transform.position + offset;
 
         if (smooth)
         {
             transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
         }
     }
 }
avatar image ThePinkPanzer MarshallN · Feb 21, 2017 at 08:01 PM 0
Share

No problem! Thank you for the effort in the first place, I appreciate it.

The character runs and follows the mouse but the camera is now static.

To be more specific, I have the Look At target on a CameraTarget set as a child to the player. I also tried setting the target as the player himself, but that also failed.

Show more comments
avatar image
0

Answer by TheRealAlakeram · Apr 11, 2018 at 11:52 PM

Did anyone solve this? if not to fix this (you'll need to change a lot more then just this, but this fixes the mouse/camera issue)

for:

          desiredPosition = lookAt.transform.position + offset;

change it to:

          desiredPosition = new Vector3(offsetForoffset.x+offset+lookAt.position.x, offsetForoffset.y+offset+lookAt.position.y, offsetForoffset.z+offset+lookAt.position.z);

this will make your mouse move the camera around the player and will also make sure the camera follows your lookAt target.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image TheRealAlakeram · Apr 11, 2018 at 11:54 PM 0
Share

i figured i would post my solution to this since thanks to this post i was able to get the camera working like how i want it :)

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

10 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Making a bubble level (not a game but work tool) 1 Answer

Mouse movement object in a straight line 2 Answers

how are Mathf.SmoothDamp and Mathf.SmoothStep different 1 Answer

Third Person Camera Help? 0 Answers

UNITY 3D: How to make the camera follow the player? Smoothly 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges