2020-11-06 00:56:50 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections;
|
2020-11-05 22:10:41 +00:00
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using UnityEngine;
|
|
|
|
|
|
|
|
|
|
// Class for following the player with the camera
|
|
|
|
|
public class CameraController : MonoBehaviour {
|
|
|
|
|
// Camera speed
|
2020-11-06 00:56:50 +00:00
|
|
|
|
public float speed = 0.1f;
|
2020-11-05 22:10:41 +00:00
|
|
|
|
// GameObject to be followed.
|
|
|
|
|
public Transform target;
|
|
|
|
|
// Our own transform
|
2020-11-06 00:56:50 +00:00
|
|
|
|
private Transform _tr;
|
2020-11-05 22:10:41 +00:00
|
|
|
|
|
|
|
|
|
// Center position of the target relative to the camera.
|
|
|
|
|
public Vector3 offset;
|
2020-11-06 01:25:10 +00:00
|
|
|
|
|
|
|
|
|
private float _goingSince;
|
|
|
|
|
private bool _goingRight;
|
2020-11-05 22:10:41 +00:00
|
|
|
|
|
|
|
|
|
// Store initial values
|
|
|
|
|
void Start()
|
|
|
|
|
{
|
2020-11-06 00:56:50 +00:00
|
|
|
|
_tr = transform;
|
|
|
|
|
offset = target.position - _tr.position;
|
2020-11-05 22:10:41 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Update positions
|
2020-11-06 00:56:50 +00:00
|
|
|
|
void FixedUpdate()
|
2020-11-05 22:10:41 +00:00
|
|
|
|
{
|
|
|
|
|
if (!target) return;
|
2020-11-06 01:25:10 +00:00
|
|
|
|
float horiz = Input.GetAxis("Horizontal");
|
|
|
|
|
if (_goingSince == 0 && Mathf.Abs(horiz) > 0.1f)
|
|
|
|
|
{
|
|
|
|
|
_goingRight = horiz > 0;
|
|
|
|
|
_goingSince = Time.time;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (Mathf.Abs(horiz) < 0.01f)
|
|
|
|
|
_goingSince = 0;
|
|
|
|
|
|
2020-11-05 22:10:41 +00:00
|
|
|
|
// Get where the camera should be, and what movement is required.
|
2020-11-06 01:25:10 +00:00
|
|
|
|
var ownPos = _tr.position;
|
|
|
|
|
Vector3 anchorPosL = ownPos + offset;
|
|
|
|
|
Vector3 anchorPosR = ownPos + new Vector3(-offset.x, offset.y, offset.z);
|
|
|
|
|
var targetPos = target.position;
|
|
|
|
|
Vector3 movementL = targetPos - anchorPosL;
|
|
|
|
|
Vector3 movementR = targetPos - anchorPosR;
|
|
|
|
|
if (movementL.x > 0 && movementR.x < 0
|
|
|
|
|
&& _goingSince == 0)
|
|
|
|
|
return;
|
|
|
|
|
var movement = (_goingSince != 0 ? _goingRight : movementL.x < movementR.x)
|
|
|
|
|
? movementL //Ha már egy ideje megyünk egy irányba vagy ha arra közelebb van a kamerának, akkor arra megy
|
|
|
|
|
: movementR;
|
|
|
|
|
|
2020-11-05 22:10:41 +00:00
|
|
|
|
// Update position based on movement and speed.
|
2020-11-06 01:25:10 +00:00
|
|
|
|
Vector3 newCamPos = ownPos + movement * speed;
|
|
|
|
|
ownPos = newCamPos;
|
|
|
|
|
_tr.position = ownPos;
|
2020-11-05 22:10:41 +00:00
|
|
|
|
}
|
|
|
|
|
}
|