- Home /
Question by
zioneig · Sep 16, 2020 at 08:49 PM ·
2d-platformercamera-movement
Created Mario like camera, now my player jitters when jumping
Originally my camera just locked onto the player and follow it at the center of the screen. When I use that code everything is fine. However I created a mario like camera that only moves when the player reaches a specific point of the screen, it works however my camera jitters all over the place when jumping, not sure if it is moving too fast for the camera but I am very confused.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CameraFollower : MonoBehaviour { public GameObject player; public Vector2 followOffset; public float speed = 10; private Vector2 threshold;
private PlayerPlatformerController playerRb;
private void Start()
{
threshold = calculateThreshold();
playerRb = player.GetComponent<PlayerPlatformerController>();
}
void FixedUpdate()
{
Vector2 follow = player.transform.position;
float xDifference = Vector2.Distance(Vector2.right * transform.position.x, Vector2.right * follow.x);
float yDifference = Vector2.Distance(Vector2.up * transform.position.y, Vector2.up * follow.y);
Vector3 newPosition = transform.position;
if(Mathf.Abs(xDifference) >= threshold.x)
{
newPosition.x = follow.x;
}
if(Mathf.Abs(yDifference) >= threshold.y)
{
newPosition.y = follow.y;
}
float moveSpeed = playerRb.GetVelocity().magnitude > speed ? playerRb.GetVelocity().magnitude : speed;
transform.position = Vector3.MoveTowards(transform.position, newPosition, moveSpeed * Time.deltaTime);
}
Vector3 calculateThreshold()
{
Rect aspect = Camera.main.pixelRect;
Vector2 t = new Vector2(Camera.main.orthographicSize * aspect.width / aspect.height, Camera.main.orthographicSize);
t.x -= followOffset.x;
t.y -= followOffset.y;
return t;
}
//draws blue box for the deadzone
void OnDrawGizmos()
{
Gizmos.color = Color.blue;
Vector2 border = calculateThreshold();
Gizmos.DrawWireCube(transform.position, new Vector3(border.x * 2, border.y * 2, 1));
}
}
Comment
Welp I gave up and found out about cinemachine, many more options much less work, thanks unity!