- Home /
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.
Answer by fafase · Apr 25, 2013 at 05:59 PM
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: http://unitygems.com/basic-ai-space-shooter/#Pattern
Cheers man I'll try and get my head round this seems like exactly what I'm trying to achieve!
Answer by Vonni · Apr 25, 2013 at 05:36 PM
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.
Your answer
Follow this Question
Related Questions
How to cap this movement? 1 Answer
Clamping rigidbody's Z position causing issues in the editor, when transform hits zero on Z axis 0 Answers
How to drag and drop a instantiate prefab on my mobile game 3D using touchs! 0 Answers
Transform position of an object at particular angle/direction 3 Answers