0
\$\begingroup\$

I am using x and z axis to go left/right ; up/down respectively. The Camera is on the y-axis.

I have the following code so far -

private float playerWidth; private float playerDepth;

private Vector2 screenBounds;

// Other Variables and Initiators


// Start is called before the first frame update
void Start()
{
    playerRigidbody = GetComponent<Rigidbody>();
    screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
    //gives x and y values that will be half the screen value. Screen coordinate system is reversed, so these will be negative values
    playerWidth = transform.GetComponent<BoxCollider>().bounds.size.x / 2;
    playerDepth = transform.GetComponent<BoxCollider>().bounds.size.z / 2;
    // we need half the size as we already are at the center of the object, using clamp
}

Tutorials are using SpriteRenderer as this would make more sense in a 2D game, however I am working in 3D space, creating a 2.5D effect.

private void LateUpdate()
    {
        withinScreenBounds();
    }

private void withinScreenBounds()
{
    // check if player does not exceed camera view, else stop all movement.
    Vector3 viewPos = transform.position;
    viewPos.x = Mathf.Clamp(viewPos.x, screenBounds.x + playerWidth, screenBounds.x * -1 - playerWidth);
    viewPos.z = Mathf.Clamp(viewPos.z, screenBounds.y + playerDepth, screenBounds.y * -1 - playerDepth);
    transform.position = viewPos;
    // the above will work with the center of the tank. 
}

The tank is currently jittering between screenpoints, not sure if this has to do with the boxcollider itself.

\$\endgroup\$
  • \$\begingroup\$ Can you show us the 2.5 D effect you're using? That term is used very loosely to describe many different perspectives and techniques, so without more information it's hard for us to know how your particular game is supposed to work. \$\endgroup\$ – DMGregory Apr 24 at 11:03
  • \$\begingroup\$ why is your viewPos.z calculation mixing y and z? \$\endgroup\$ – Zibelas Apr 24 at 14:39
  • \$\begingroup\$ Mostly I am mixing the axes, as my top down shooter is using x and z in world space, and in screenspace this translates to x and y. @DMGregory top down effect is identical to SkyForce Reloaded. 3D Models from a 2D top down perspective. \$\endgroup\$ – firepro20 Apr 29 at 7:06
  • \$\begingroup\$ apologies for the late response, got some time to work on it over the weekend. Essentially I just want to keep the player from going off screen i.e. go behind the camera, since I'm locking the Z-Position to only move in the forward direction if the player goes in the upward/forward transform. \$\endgroup\$ – firepro20 Apr 29 at 7:08

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.