Camera move when reach edge of screen

Hello there.

I am trying to make the camera move when it reaches the edge of the screen.

I have this:

using UnityEngine;
using System.Collections;

public class CamMouse : MonoBehaviour
{
public void Update()
{
    transform.position = new Vector3(
          Input.mousePosition.x,
          0,
          Input.mousePosition.y);

}

}

So how do i make it only move when it reaches the edge of the screen.
And not just follow the mouse.
So if the mouse reaches the edge to the right the camera will go right.

Also i have a problem with that when i start playing the game, the y position of the camera sets to 0??

  • Frederik

Check my answer to the same question here :

http://answers.unity3d.com/questions/266454/top-down-2d-gamehow-to-make-the-camera-move-on-hit.html

and here :

http://answers.unity3d.com/questions/275436/move-the-camera-then-the-cursor-is-at-the-screen-e.html

This is what I use in my RTS game:

var edgeDist : float = 50.0; //pixels
var moveSpeed : float = 10.0;
var rotateSpeed : float = 20.0;
var height : float = 25.0;
var heightChangeSpeed : float = .1;

function Update () {
	var hit : RaycastHit;
	if (Physics.Raycast(transform.position, transform.forward, hit, Mathf.Infinity, Layers.CreateInclusiveMask([Layers.scape]))) {
		transform.position = Vector3.Lerp(transform.position, hit.point - transform.forward*height*(Input.GetKey("z") ? 4.0 : 1.0), 0.1);
	}
	transform.RotateAround(hit.point, Vector3.up, Input.GetAxis("Camera Rotate")*rotateSpeed*Time.deltaTime);
	
	height = height * (-Input.GetAxis("Mouse ScrollWheel")*heightChangeSpeed + 1);
	
	var move : Vector3 = Vector3(Input.GetAxis("Horizontal"),Input.GetAxis("Vertical"),0);
	if (Input.mousePosition.x < edgeDist) move.x=-1;
	if (Input.mousePosition.x > Screen.width- edgeDist) move.x=1;
	if (Input.mousePosition.y < edgeDist) move.y=-1;
	if (Input.mousePosition.y > Screen.height- edgeDist) move.y=1;
	move *= moveSpeed * height;
	
	move = transform.rotation * move;
	move.y=0;
	transform.position += move * Time.deltaTime;
	

why not check the mouse x position and do something like:


if ( Input.mouseposition.x <20 ) {
   //rotate camera left here
}
if ( Input.mouseposition.x >Screen.width -20 ) {
   //rotate camera right here
}

the 20 is the number of pixels that will be at the sides and the whole section of code should be in the function Update()… function call :slight_smile:

You can move the camera where you want in the Inspector or in code if you have a variable:


var Cam:Camera;

then attach your camera in the inspector to the variable Cam then in code you can change anything about it with commands like:


Cam.transform.position = Vector3( -50, 50, 20 ); //this will move it to X:-50, Y:50 Z:20

:smiley: