Finding local position and clamping movement

Hey!
I’m trying to create a fish enemy and want it to float up and down slightly while moving horizontally. I’ve tried to find it’s position once it is created. With this position I try and keep it at relatively the same height moving it up and down slightly. At the moment it only moves down and not back up again.

//Inspector Variables.
var fish01HorizontalSpeed = 6;
var fish01Position = 0;
var fish01VerticalSpeed = 0.5;

function Start () {
fish01Position = transform.position.y;

}

function Update () {
//Initiates movement to the right on the x axis.
transform.Translate(Vector3.up * fish01HorizontalSpeed * Time.deltaTime);
transform.Translate(Vector3.right * fish01VerticalSpeed * Time.deltaTime);
//Checks for horizontal position of fish and reverse direction.
if (transform.position.x >= 15)
{
fish01HorizontalSpeed = -6;
}
if (transform.position.x <= -15)
{
fish01HorizontalSpeed = 6;
}
//Check for vertical position of fish and reverse direction
if (transform.position.y >= fish01Position + 1)
{
fish01VerticalSpeed = -0.5;
}
if (transform.position.y <= fish01Position + -1)
{
fish01VerticalSpeed = 0.5;
}

}

I think you have your horizontal and vertical switched on the transform.Translate part of your script.

I tested horizontal movement before I added vertical. So this is not the problem.

2 Answers

2

Swap Vector3.right and Vector3.up . I can’t see it being anything else here!, what is up in your scene?

Swapped and it just fell off the screen. It does the same on my desktop at home and axis seem to be inverted or something it's strange.

I would recommend to use a cos/sin function:

void Update(){
    index += Time.deltaTime;
    float zPos=amplitude*(Mathf.Cos(omega*index))*Time.deltaTime;
    _transform.Translate ( -velocity.x*Time.deltaTime,0,zPos,Space.World);
}

You can have a look there for more info:

Cheers man I'll try and get my head round this seems like exactly what I'm trying to achieve!