Let me state that I’m working with 2D at the beginning. So I’ve got this (pretty ugly I know, but bear with me) almost working piece of code, which, if the object exits the camera’s FOV, movesthe object to the other side of the screen, while the whole script is able to adapt to different screen ratios.
The problem I’m having is with the offscreen offset. Although it works as intended when calculating WHEN the object should be moved, it doesn’t do anything when calculating WHERE the object should be moved TO. I’ve tried all kinds of grouping the calculations with parentheses but everything just produces the same result, which is moving the object right to the edge of the screen. What could the problem be?
using UnityEngine;
using System.Collections;
public class Teleportation : MonoBehaviour
{
public Rigidbody2D rb;
public Camera camera;
public float offscreenOffset = 1f;
private float verticalBoundary;
private float horizontalBoundary;
private Vector2 newPosition;
private Vector2 currentSpeed;
private Vector2 oldPosition;
void Start()
{
verticalBoundary = camera.orthographicSize;
horizontalBoundary = camera.orthographicSize * camera.aspect;
}
void Update()
{
if (rb.position.x > horizontalBoundary + offscreenOffset)
{
oldPosition = rb.position;
newPosition = new Vector2(oldPosition.x - offscreenOffset - (horizontalBoundary * 2), oldPosition.y);
currentSpeed = rb.velocity;
rb.position = newPosition;
rb.velocity = currentSpeed;
}
if (rb.position.x < -horizontalBoundary - offscreenOffset)
{
oldPosition = rb.position;
newPosition = new Vector2(oldPosition.x + offscreenOffset + (horizontalBoundary * 2), oldPosition.y);
currentSpeed = rb.velocity;
rb.position = newPosition;
rb.velocity = currentSpeed;
}
if (rb.position.y > verticalBoundary + offscreenOffset)
{
oldPosition = rb.position;
newPosition = new Vector2(oldPosition.x, oldPosition.y - offscreenOffset - (verticalBoundary * 2));
currentSpeed = rb.velocity;
rb.position = newPosition;
rb.velocity = currentSpeed;
}
if (rb.position.y < -verticalBoundary - offscreenOffset)
{
oldPosition = rb.position;
newPosition = new Vector2(oldPosition.x, oldPosition.y + offscreenOffset + (verticalBoundary * 2));
currentSpeed = rb.velocity;
rb.position = newPosition;
rb.velocity = currentSpeed;
}
}
}
I think the currentSpeed and oldPosition variables could be left out, but I’m using them to prevent any bugs.