Hello I`m looking for a way for my Ship gameobject to move randomly on the x or both x and z axis in a boundary. I tried a few times but failed>wonder if anyone can help me, would be great , thanks ^^
You can use the add force method with random values , here’s a snippet:
`
RigidBody rb;
void Start(){
rb = getComponent();
}
void FixedUpdate(){
//remove any existing force
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
//add a new force with random value
rb.addForce(new Vector3(Random.value , 0 , Random.value) * required_speed);
}`
For the gameObject to be within boundaries , let the colliders do the work.
If your ship moves on a flat surface, then try this:
using UnityEngine;
public class RandomMovement : MonoBehaviour
{
public float moveSpeed = 2;
public float turnSpeed = 45;
public Transform minX = null;
public Transform maxX = null;
public Transform minZ = null;
public Transform maxZ = null;
private Vector3 position = Vector3.zero;
private void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))if(minX && maxX && minZ && maxZ)RandomizePosition();
MoveGameObject();
}
private void RandomizePosition ()
{
position = new Vector3(Random.Range(minX.position.x,maxX.position.x),transform.position.y,Random.Range(minZ.position.z,maxZ.position.z));
}
private void MoveGameObject ()
{
Vector3 angle = position - transform.position;
if(angle.y != 0)angle.y = 0;
if(position.y != transform.position.y)position.y = transform.position.y;
if(transform.position != Vector3.MoveTowards(transform.position,position,moveSpeed * Time.deltaTime))
{
transform.position = Vector3.MoveTowards(transform.position,position,moveSpeed * Time.deltaTime);
transform.rotation = Quaternion.RotateTowards(transform.rotation,Quaternion.LookRotation(angle),turnSpeed * Time.deltaTime);
}
}
}
Just press Space button and it will move to a new random position.
If your ship doesn’t move on a flat surface, then you have to modify the position.y by your self.
Thank you for the responses but I did it with the NavMeshAgent and it works brilliant.