Hi Unity Community,
Im currently trying to create a set up where a school of fish move to the right side of the screen when I press D
and the left side when I press A
, returning to their original position after 15 seconds. My current code works, however I now want to create some idle movement, where the fish swim around randomly, all moving to one side when the D
or A
is used. I have used a set I purchased online with prefabs, so Im not looking to animate anything, more just give them movement. I have no idea where to start with this, and many tutorials online are not beginner friendly.
Heres my current code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class MovetoCoords : MonoBehaviour
{
public KeyCode Right = KeyCode.D;
public KeyCode Left = KeyCode.A;
public KeyCode Return = KeyCode.W;
public float Step = 10;
public float smoothness = 0.1f;
public float rotationSpeed = 0.05f;
private Vector3 originalPosition;
private Vector3 targetPosition;
private bool movingRight = false;
private bool movingLeft = false;
private bool returning = false;
private float elapsedTime = 0f;
private float returnTime = 15f;
void Start()
{
originalPosition = transform.position;
targetPosition = originalPosition;
}
void Update()
{
elapsedTime += Time.deltaTime;
if (elapsedTime >= returnTime)
{
returning = true;
targetPosition = originalPosition;
elapsedTime = 0f;
}
if (Input.GetKeyDown(Right))
{
movingRight = true;
targetPosition = transform.position + new Vector3(Step, 0, 0);
}
if (movingRight)
{
MoveAndRotate();
}
if (Input.GetKeyDown(Left))
{
movingLeft = true;
targetPosition = transform.position - new Vector3(Step, 0, 0);
}
if (movingLeft)
{
MoveAndRotate();
}
if (returning)
{
MoveAndRotate();
}
}
void MoveAndRotate()
{
transform.position = Vector3.Lerp(transform.position, targetPosition, smoothness * Time.deltaTime);
Vector3 direction = (targetPosition - transform.position).normalized;
if (direction != Vector3.zero)
{
Quaternion toRotation = Quaternion.LookRotation(direction, Vector3.up);
transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, rotationSpeed);
}
if (transform.position == targetPosition)
{
movingRight = false;
movingLeft = false;
returning = false;
}
}
}