Clamping Makes My Ship Disappear

Hi, I have tried searching online for this but can’t find any solutions. After implementing the code and once I hit play my ship disappears. When go back to the code and comment out the clamping code and then hit play my ship stays but I am unable to move it (obviously). Does anyone know why my ship is disappearing once I hit play?
I even tried using the newer input method but that gave me the same issue.

Video showing problem

Here is my code (and thank you in advance for any help):

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

public class PlayerControls : MonoBehaviour
{

[SerializeField] float controlSpeed = 10f;
[SerializeField] float xRange = 5f;
[SerializeField] float yRange = 3.5f;

// Update is called once per frame
void Update()
{
    float xThrow = Input.GetAxis("Horizontal");
    float yThrow = Input.GetAxis("Vertical");

    float xOffset = xThrow * Time.deltaTime * controlSpeed;
    float rawXPos = transform.localPosition.x + xOffset;
    float clampedXPos = Mathf.Clamp(rawXPos, -xRange, xRange);

    float yOffset = yThrow * Time.deltaTime * controlSpeed;
    float rawYPos = transform.localPosition.y + yOffset;
    float clampedYPos = Mathf.Clamp(rawYPos, -yRange, yRange);

    transform.localPosition = new Vector3(clampedXPos, clampedYPos, transform.localPosition.z);
}

}

I would guess that your ship’s local positional values are either higher or lower than the ranges you’re clamping it to with the xRange and/or yRange values.

For example, if the ship’s transform.localPosition.y is set to 100, when the game starts it will be set to the maximum yRange value of 3.5 instead, moving it 96.5 units lower and giving the appearance that it has vanished as it’s likely not within sight (for example it could be hidden below the terrain).

The video shows that in your hierarchy the Player Ship is not childed under the Player Rig, so another possible issue is that the Timeline is animating the Rig and not the Ship. If you’re counting on the Timeline to set the Player Ship to the right starting position, make sure that’s set up correctly.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms