- Home /
Having trouble moving object in opposite direction of player.
Working on a game mechanic in 2D and I cant seem to figure out how to get an object to follow the players input but in opposite directions. I have the same direction figured out for one object, but opposite is giving me problems. For example, as soon as I start moving, the object that is suppose to be opposite flies to the top of the screen then starts moving in the opposite directions correctly. Where as the normal object works just fine.
Heres the code:
private void FixedUpdate() {
if (isMoving)
{
if (isRed)
{
targetPosition = player.transform.position + startPosition; // Red Box (Works Great)
transform.position = targetPosition;
}
else
{
targetPosition = player.transform.position + startPosition; // Blue Box (Broken)
transform.position = -targetPosition;
}
}
else
{
startPosition = transform.position - player.transform.position; // Return to resting position
transform.position = player.transform.position + startPosition;
}
}
I think it may have something to do with it being because its a vector 3, the -y position is being applied and moving it into the air opposite of where it would be. However I'm not sure how I would fix this without tracking y position for the object that needs to move in opposite of the player. Any ideas on what I can do?
Answer by mudabbirali92 · Jul 31, 2019 at 11:42 AM
int direction = 1
private void FixedUpdate() {
if (isMoving)
{
if (isRed)
{
targetPosition = player.transform.position + startPosition*direction;
transform.position = targetPosition;
}
else
{
targetPosition = player.transform.position + startPosition*-direction;
transform.position = targetPosition;
}
}
else
{
startPosition = transform.position - player.transform.position;
transform.position = player.transform.position + startPosition;
}
}
Hope this would help. :)
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Move game object in opposite direction of player in x & y axis? (2D Game) 0 Answers
How to check if an object hits the ground hard enough then add explosive force around it (2D) 1 Answer
Distribute terrain in zones 3 Answers
The player randomly freezes in place while other objects move ingame 1 Answer