- Home /
Question by
SrLuquitas · Feb 28, 2021 at 12:18 AM ·
camera2drts
Center camera at player Unity 2D,How to make the camera center at the player? Unity 2D
Hi, im making a MOBA game in Unity 2D, and i have an RTS camera type, im trying to make my camera center at the player when i press space but i cant do it (When i press space the camera go crazy), can you help me? here is the camera code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform target;
public float offset;
public float speed;
//x - min y - max
public Vector2 minMaxXPosition;
public Vector2 minMaxYPosition;
private float screenWidth;
private float screenHeight;
private Vector3 cameraMove;
// Use this for initialization
void Start()
{
screenWidth = Screen.width;
screenHeight = Screen.height;
cameraMove.x = transform.position.x;
cameraMove.y = transform.position.y;
cameraMove.z = transform.position.z;
}
// Update is called once per frame
void Update()
{
//Move camera
if ((Input.mousePosition.x > screenWidth - offset) && transform.position.x < minMaxXPosition.y)
{
cameraMove.x += MoveSpeed();
}
if ((Input.mousePosition.x < offset) && transform.position.x > minMaxXPosition.x)
{
cameraMove.x -= MoveSpeed();
}
if ((Input.mousePosition.y > screenHeight - offset) && transform.position.y < minMaxYPosition.y)
{
cameraMove.y += MoveSpeed();
}
if ((Input.mousePosition.y < offset) && transform.position.y > minMaxYPosition.x)
{
cameraMove.y -= MoveSpeed();
}
transform.position = cameraMove;
if (Input.GetKey(KeyCode.Space))
{
CenterAtPlayer();
}
}
float MoveSpeed()
{
return speed * Time.deltaTime;
}
void CenterAtPlayer()
{
transform.right = target.position - transform.position;
}
}
Comment
Best Answer
Answer by $$anonymous$$ · Feb 28, 2021 at 01:53 AM
Try this :
Vector2 targetPos = new Vector2 (target.position.x, target.position.y, transform.position.z);
transform.position = targetPos;
Thank you so much! This works, but now i have another problem, i want the camera to stay in the player position, but when I press space, it just teleports to the player position for a moment and then go back to the original position. Do you know what is the problem?
It will keep the z position the same but will snap to the target position
If you want a Move towards the target and center use :
Vector2 targetPos = new Vector2 (target.position.x, target.position.y, transform.position.z);
transform.position = Vector2.MoveTowards (transform.position, targetPos, cameraMoveSpeed * Time.deltaTime);
Your answer
![](https://koobas.hobune.stream/wayback/20220613025921im_/https://answers.unity.com/themes/thub/images/avi.jpg)