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 nikolahack0 · Nov 05, 2015 at 01:17 PM · cameramovementcharactertopdown

Make a camera move towards player when the player moves out of the camera's vision

I am making a top down/bird perspective game.

My player character can move around and I can turn the player around 360.

But what I am missing is a way for the camera to follow the Player.

I know that I can make my camera the child of the player character so it follows it but that makes my player spin uncontrolled because of the way the rotation works with the camera.

Script:

     using UnityEngine;
     using System.Collections;
 
     public class PlayerScript : MonoBehaviour {
 
     Rigidbody rigidBody;
     public float speed = 4;
 
     Vector3 lookPos;
 
     void Start () 
     {
         rigidBody = GetComponent<Rigidbody>();
     }
 
 
     void Update () 
     {
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         
         RaycastHit hit;
         
         if (Physics.Raycast (ray, out hit, 100))
         {
             lookPos = hit.point;
         }
     
         Vector3 lookDir = lookPos - transform.position;
         lookDir.y = 0;
 
         transform.LookAt (transform.position + lookDir, Vector3.up);
     }
 
     void FixedUpdate ()
     {
         float horizontal = Input.GetAxis ("Horizontal");
         float vertical = Input.GetAxis ("Vertical");
 
         Vector3 movement = new Vector3 (horizontal, 0, vertical);
 
         rigidBody.AddForce (movement * speed / Time.deltaTime);
 
     }
         }



I need a solution:

  • Make the camera move as the player gets out of its vison.

  • New player movement script

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
1

Answer by Garazbolg · Nov 05, 2015 at 02:32 PM

For the Camera following script you can set a script on the camera to folow the Player like this :

 public class CameraFollow  : MonoBehaviour
 {
     public Transform target;
     public float speed = 0.7f;
 
     public void Start(){
         target = GameObject.FindGameObjectsWithTag("Player")[0].transform;
     }
 
     public void Update(){
         transform.position = Vector3.Lerp(transform.position,new Vector3(target.position.x,transform.position.y,target.position.z),speed * Time.deltaTime);
     }
 }

You can change the speed value to suit your needs. This script is pretty basic i think i saw it on the first Unity Tutorial I've seen.

For the other i didn't understand what you were saying, could you be more clear.

Comment
Add comment · Show 2 · 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 nikolahack0 · Nov 05, 2015 at 06:52 PM 0
Share

I tough the script would be good in the beginning, It was. But now I have a few problems actually: IndexOutOfRangeException: Array index is out of range. CameraFollowScript.Start () (at Assets/Player Controller/CameraFollowScript.cs:10)

I get that error, and also the camera movement is kind of buggy in the sense that it does not go smooth. I can see it on my flashlight of the player.

avatar image Garazbolg nikolahack0 · Nov 06, 2015 at 08:54 AM 0
Share

Yeah i forgot to say that : you need to set the tag on your player GameObject to "Player" if you don't it won't work, and if you don't have a Player at the moment of the Camera Start it won't work.

A cleaner way to do :

 target = GameObject.FindGameObjectsWithTag("Player")[0].transform;

would be to do :

 GameObject player = GameObject.FindWithTag("Player");
 
 if(player)
     target = player.transform;


and add in your update some way to check if there is a target :

 public void Update(){
         if(target)
          transform.position = Vector3.Lerp(transform.position,new Vector3(target.position.x,transform.position.y,target.position.z),speed * Time.deltaTime);
      }


But then if you don't have a Player at the start your Script won't do anything, unless you set the target attribute of CameraFollow somewhere else (in the start of your Player Script for exemple)

 void Start () 
      {
          rigidBody = GetComponent<Rigidbody>();
          CameraFollow camera = Camera.main.GetComponent<CameraFollow>();
          if(camera)
              camera.target = transform;
      }


I did the previous script quickly but you may want to look at the documentation of Unity and some manuals to understand how it works.

avatar image
0

Answer by DeathDev · Nov 06, 2015 at 12:06 AM

This should work, let me know if you have any problems. :)
PS - If you don't want to wait for the character to leave the screen before the camera moves, simply remove the if statement inside of the Update function. Also if you need a more complex version(for instance one that actually makes sure that the entire player is inside of the bounds, let me know!)
using UnityEngine; using System.Collections;

 public class CameraMovement : MonoBehaviour
 {
     public Transform playerObject;
     public float moveSpeed = 1;
 
     public bool keepHeight = true; //If we should keep the current height.
     public bool dispArea = true;   //If we should display the cam area.
 
     public float buffer = 20;    //The area(in pixels) around the edges that'll cause the camera to move.
 
     private Vector3 _pos;   //The cached pos.
     private Rect _moveArea; //If the obj exits this area, we'll move to catch up.
 
     //Setting the playerObject to the scene's player object, along with caching the height.
     void Start() 
     { 
         playerObject = GameObject.FindGameObjectWithTag("Player").transform;
         _pos = transform.position;
 
         //Setting our camera area.
         _moveArea.x = ((Screen.width / 2) - buffer / 2);
         _moveArea.width = buffer;
         _moveArea.y = ((Screen.height / 2) - buffer / 2);
         _moveArea.height = buffer;
     }
 
     void Update()
     {
         if (!vecInArea(playerObject.position))
         {
             Vector3 _newPos = playerObject.position;
             if (keepHeight)
                 _newPos.y = _pos.y;
             transform.position = Vector3.Lerp(transform.position, _newPos, moveSpeed * Time.deltaTime);
         }
     }
 
     bool vecInArea(Vector3 pos)
     {
         Vector2 screenPos = Camera.main.WorldToScreenPoint(pos);
         return _moveArea.Contains(screenPos);
     }
 
     void OnGUI() { if (dispArea) GUI.color = new Color(1.0f, 1.0f, 1.0f, 0.25f); GUI.Box(_moveArea, ""); }
 }

As Garazbolg said, more information is needed for the second point.

Comment
Add comment · 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

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Smooth Camera Movement script with problem. 0 Answers

Change character's Y rotation based on velocity. 1 Answer

Camera Zoom script stops ability to pan 1 Answer

Camera move with mouse 0 Answers

change move controls relative to player 1 Answer


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