1
\$\begingroup\$

I am new to Game Dev.

I am trying to make a asteroid shooter like game with screen wrap (in unity 2017.4)

But the screen wrap code is not working well

View Faulty Screen wrap in action by clicking the Video Link.

Instead of teleporting the the object to the other side of the screen it is choosing a random point.

I made a classic WASD movement and point towards mouse script.

Then I put the following script on the player with guidance from envato tuts +

Script for reference👇️

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScreenWrapper : MonoBehaviour
{
   Renderer[] renderers;
   public Camera mainCamera;
   Vector3 newPos;

   Vector3 viewPortPos;

   void Start()
   {
      renderers = GetComponentsInChildren<Renderer>();
      newPos = transform.position;
   }

   bool isOffScreen()
   {
      foreach (Renderer renderer in renderers)
      {
         if (renderer.isVisible)
         {
            return false;
         }
      }

      return true;
   }

   void Update()
   {

      viewPortPos = mainCamera.WorldToViewportPoint(transform.position);

      if (isOffScreen())
      {
         if (viewPortPos.x > 1 || viewPortPos.x < 0)
         {
            newPos.x = -newPos.x;
         }

         if (viewPortPos.y > 1 || viewPortPos.y < 0)
         {
            newPos.y = -newPos.y;
         }

         transform.position = newPos;
         newPos = transform.position;
      }
   }
}

Download Project for reference by clicking the link.

Hope you Help me figure out my mistake.

\$\endgroup\$
2
  • \$\begingroup\$ It won't answer your question, but Unity 2017 is pretty outdated now. You should consider updating to 2019.4.x or 2020.3.x \$\endgroup\$ – Kevin Jun 3 at 0:11
  • \$\begingroup\$ But due to some reason my Windows PC(64-bit, 4GB RAM) is handling unity versions greater than 2017 very slow. \$\endgroup\$ – BALAJI VIJAYAN Jun 3 at 4:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.