UnityProjekt/Assets/CameraController.cs

54 lines
1.6 KiB
C#
Raw Normal View History

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
public float speed = 0.1f;
2020-11-05 22:10:41 +00:00
// GameObject to be followed.
public Transform target;
// Our own transform
private Transform _tr;
2020-11-05 22:10:41 +00:00
// Center position of the target relative to the camera.
public Vector3 offset;
private float _lastSwitch = -1;
private bool _facingRight;
2020-11-05 22:10:41 +00:00
// Store initial values
void Start()
{
_tr = transform;
offset = target.position - _tr.position;
2020-11-05 22:10:41 +00:00
}
// Update positions
void FixedUpdate()
2020-11-05 22:10:41 +00:00
{
if (!target) return;
// Get where the camera should be, and what movement is required.
var position = _tr.position;
bool facingLeft = target.localScale.x < 0;
Vector3 anchorPos = position + (facingLeft ? new Vector3(-offset.x, offset.y, offset.z) : offset);
2020-11-05 22:10:41 +00:00
Vector3 movement = target.position - anchorPos;
float sp = speed;
/*if (_lastSwitch >= 0 && Time.time - _lastSwitch < 0.5f)
sp /= 4;*/
float diff = Time.time - _lastSwitch;
if (_lastSwitch >= 0 && diff < 2f)
sp *= 0.5f + diff / 4;
if (facingLeft == _facingRight) //Megváltozott az irány
_lastSwitch = Time.time;
_facingRight = !facingLeft;
2020-11-05 22:10:41 +00:00
// Update position based on movement and speed.
Vector3 newCamPos = position + movement * sp;
2020-11-05 22:10:41 +00:00
position = newCamPos;
_tr.position = position;
2020-11-05 22:10:41 +00:00
}
}