- Home /
Moving an object based on position of other object
Hi,
I am creating a Pong game where I have two bars and the movement of first bar (Player 1) is generated by the system whereas the user would control the other bar (Player 2). The goal of both the players is to hit the ball which is moving between the two bars.
I am writing the code to move Player 1 based on position and velocity of the ball. The code works fine and Player 1 in most cases reaches the expected position of the ball. But in some cases, I see Player 1 going through a very rapid zig-zag movement even though the expected position of the ball is not changing.
The following is my code to compute the position of Player 1. This code is inside the update method of the ball.In only compute the Y position, because on the X asis player 1 remains stationary. I only change position of player 1 if the ball is moving towards it (i.e. if rigidbody2D.velocity.x < 0)
if(rigidbody2D.velocity.x < 0){
var player1X:float = player1.position.x;
var player1Y:float = player1.position.y;
var midHeight:float = player1.lossyScale.y / 2;
var ballX:float = transform.position.x;
var ballY:float = transform.position.y;
var timeToMove:float = (player1X - ballX) / (rigidbody2D.velocity.x);
var expectedYBall:float = rigidbody2D.velocity.y * timeToMove + ballY;
if(player1Y + midHeight - 0.2 < expectedYBall){
player1.rigidbody2D.velocity.y = 10;
}
else if(player1Y - midHeight + 0.2 > expectedYBall){
player1.rigidbody2D.velocity.y = -10;
} else {
player1.rigidbody2D.velocity.y = 0;
}
}
Attached herewith is screenshot for your reference. Please let me know if I am missing something.
Answer by BsseeJ · Jun 22, 2014 at 11:00 PM
I'm not entirely sure what's wrong because I'm new myself, but I'd suggest looking into these two functions.
This may work better than using velocity http://docs.unity3d.com/ScriptReference/Vector2.MoveTowards.html or http://docs.unity3d.com/ScriptReference/Vector2-up.html
I got the impression that you were saying the zigzag was on the x axis but I'm not sure, if that's so you can try this. http://docs.unity3d.com/ScriptReference/Mathf.Clamp.html You can use mathf.clamp to clamp an axis in transform.
I wish I understood Java better so I could write up where I'd replace the code but maybe that documentation will help anyways. Good luck, hope I was of any help.
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Scripts accessing one another (JS) 0 Answers
how can I display a variable as a GUIText 5 Answers
Checking if a position is occupied in 2D? 1 Answer
Why does "Optimize Game Objects" break my armature and animations? 1 Answer