This question was
closed Jul 28, 2020 at 04:42 PM by
Lominoe for the following reason:
I posted another question with an updated script.
Question by
Lominoe · Jul 28, 2020 at 03:23 AM ·
c#camera-movement
How can i center my camera on my player?
So I have a script that moves my camera in the direction of my mouse but the camera can only move a certain distance away. Right now, the camera is centered on the origin of the screen and the mouse moves the camera correctly but I cant figure out how to center the camera on the player instead of the origin. Sorry if this is a common sense, I started programming recently.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraScript : MonoBehaviour
{
//The speed of the movement
public float cameraSpeed = 0.5f;
public float speedOfIncrease = 3;
//Min and max-values the camera can move to.
private float MAX_X = 6;
private float MIN_X = -6;
private float MAX_Y = 3;
private float MIN_Y = -3;
//The current x and y movement of the cursor
private float Xmouse;
private float Ymouse;
void Update()
{
Xmouse = Input.GetAxis("Mouse X");
Ymouse = Input.GetAxis("Mouse Y");
Vector3 v3 = Input.mousePosition;
v3.z = transform.position.z;
v3 = Camera.main.ScreenToWorldPoint(v3);
Vector3 newPos = transform.position;
newPos.x += Xmouse * speedOfIncrease;
newPos.y += Ymouse * speedOfIncrease;
//Making sure that the camera doesn't exceed the min/max values it's allowed to move to!
if (newPos.x > MAX_X)
{
newPos.x = MAX_X;
}
if (newPos.x < MIN_X)
{
newPos.x = MIN_X;
}
if (newPos.y > MAX_Y)
{
newPos.y = MAX_Y;
}
if (newPos.y < MIN_Y)
{
newPos.y = MIN_Y;
}
//Moves the Camera
transform.position = Vector3.Lerp(transform.position, newPos, cameraSpeed * Time.deltaTime);
}
}
Comment
Answer by Llama_w_2Ls · Jul 28, 2020 at 11:28 AM
public Camera MainCam;
public GameObject player;
private void FixedUpdate()
{
MainCam.transform.position = new Vector3(player.transform.position.x, player.transform.position.y, MainCam.transform.position.z);
//You dont want the camera's z position to be the same as the player, just the x and y.
//Locks camera position to the centre of the player
}
Follow this Question
Related Questions
Camera Tracking 1 Answer
How to make an object go the direction it is facing? 0 Answers
How can I get my camera to move properly? 0 Answers
Camera Jitters When Displacing and Rotating Smoothly 0 Answers
Smoth LookAt Unity c# 0 Answers