Question by
Franc3spo · May 09 at 03:34 PM ·
scripting problemmovementscript.scripting beginner
Rigidbody2D movement is lagging
Hi I am trying to make a UFO move relative to when the player moves. I have already tried with interpolate and extrapolate, and even using only transform positions. Any suggestions?
I'd like to add that the movement only strutters when the player moves slowly.
using UnityEngine;
public class UFOBehaviour : MonoBehaviour
{
[SerializeField] float minDistance;
[SerializeField] float maxDistance;
[SerializeField] float minSpeed;
float speed;
[SerializeField] Rigidbody2D playerRb;
Rigidbody2D ufoRb;
GameObject player;
Vector2 playerPos;
float distance;
private void Awake()
{
ufoRb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
playerPos = playerRb.position;
distance = Vector2.Distance(playerPos, ufoRb.position);
GameManager.FixPosition(ufoRb); // This is used to make the UFO teleport when out of screen bounds
if (playerRb.velocity.magnitude > minSpeed) speed = playerRb.velocity.magnitude;
else speed = minSpeed;
RefreshPos1();
}
void RefreshPos1()
{
if (distance > maxDistance)
{
ufoRb.position = Vector2.MoveTowards(ufoRb.position, playerPos, speed * Time.fixedDeltaTime);
}
else if (distance < minDistance)
{
ufoRb.position = Vector2.MoveTowards(ufoRb.position, playerPos, -speed * Time.fixedDeltaTime);
}
}
}
Comment