Reputation: 59
i am creating a 2d game where my camera position y axis has to be changed/decreased according to its current y position.
public void continuebut()
{
campos = 0;
campos = transform.position.y;
if (campos <0)
{
campos += 4;//negative y position so the result will decrease the y position
transform.Translate(0, campos, 0);
}
else
{
campos -= 4;//positive y position so the result will decrease the y position
transform.Translate(0, campos, 0);
}
}
i expect the positive y position to be decreased but this code increase the y position of the camera instead of bringing down in y its going up. but it is not what i expected.i want the camera position y to go down when its a non negative number.
Upvotes: 0
Views: 134
Reputation: 1102
First of all,
campos=0;
is pointless since it is immediately followed by:
campos=transform.position.x;
In fact, the compiler probably skips it completely and that line does not get in the final code.
About the rest of the code, you need to rethink what you are actually commanding to your app. You first take your y axis position. Let's suppose
transform.position.y=5.0f;
So,
campos=5.0f;
Since
campos>0.0f
Your app does reduce campos
campos-=4;
So campos becomes 5-4=1.0f Now, you do
campos.Traslate(0,1.0f,0);
So you are basically moving your object UP. What you might want to do instead is
transform.Translate(0,-4.0f,0);
However, consider that you probably would end up getting an oscillating object when it gets close to 0, oscillating every frame 4 units up and down.
Upvotes: 1
Reputation: 74
I may be off, but i think you're talking about this:
public void continuebut()
{
campos = 0;
campos = transform.position.y;
if (campos >0)
{
// If camera position is positive
// Decrease camera y position
campos -= 4;//positive y position so the result will decrease the y position
//Translate camera position
transform.Translate(0, campos, 0);
}
else
{
// If camera position if negative or zero
// Increase camera y position
campos += 4;//negative y position so the result will increase the y position
//Translate camera position
transform.Translate(0, campos, 0);
}
}
Upvotes: 1