I am trying to restrict the movement of my object by only running my movement code if the object is within the bounds of a cube. This works fine for stopping my object at the bounds of the cube, but I can’t figure out how to all movement, just not beyond the bounds.
I tried to just offset my object when it reached the bounds but that doesn’t seem to move my object at all, I may be approaching it wrong.
Here is my script, it’s a bit simple and probably not very efficent, I’m still learning.
Thanks for any help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShipMovement : MonoBehaviour
{
public float moveSpeed = 10f;
public float turnSpeed = 10f;
Transform myT;
private float myTx;
private float myTy;
private float myTz;
public Collider flyZone;
private Vector3 minFly;
private Vector3 maxFly;
private bool hasFlyZone = false;
private bool inFlyZone = false;
private void Awake()
{
myT = transform;
if (flyZone != null)
{
hasFlyZone = true;
minFly = flyZone.bounds.min;
maxFly = flyZone.bounds.max;
}
}
void Update()
{
Thrust();
Turn();
}
void Turn()
{
float pitch = turnSpeed * Time.deltaTime * Input.GetAxis("Pitch");
float yaw = turnSpeed * Time.deltaTime * Input.GetAxis("Horizontal");
float roll = turnSpeed * Time.deltaTime * Input.GetAxis("Roll");
myT.Rotate(pitch, yaw, roll);
}
void Thrust()
{
if (Input.GetAxis("Vertical") > 0)
{
{
myTx = myT.position.x;
myTy = myT.position.y;
myTz = myT.position.z;
if (hasFlyZone && myTy > minFly.y && myTy < maxFly.y && myTx > minFly.x && myTx < maxFly.x && myTz > minFly.z && myTz < maxFly.z)
{
inFlyZone = true;
}
else inFlyZone = false;
if (inFlyZone)
{
Debug.Log("Inside FlyZone!");
myT.position += myT.forward * moveSpeed * Time.deltaTime * Input.GetAxis("Vertical");
}
if (myTx < minFly.x)
{
myTx = minFly.x +5;
Debug.Log("Moved in");
}
if (myTx > maxFly.x)
{
myTx = maxFly.x -5;
Debug.Log("Moved in");
}
if (myTy < minFly.y)
{
myTy = minFly.y +5;
Debug.Log("Moved in");
}
if (myTy > maxFly.y)
{
myTy = maxFly.y -5;
Debug.Log("Moved in");
}
if (myTz < minFly.z)
{
myTz = minFly.z +5;
Debug.Log("Moved in");
}
if (myTz > maxFly.z)
{
myTz = maxFly.z -5;
Debug.Log("Moved in");
}
}
}
}
}