- Home /
Having a goalie follow the ball but not move towards it
Hey, I'm making a 3d soccer game where the player shoots the ball at a net and the goalie tries to save it. I'm trying to have the goalie follow the ball but stay within his net, but currently he can move forward and hit the ball away from the player. I just want him to block the shots the player takes.
Answer by metalted · Apr 10, 2019 at 04:38 PM
Well lets assume that you shoot the ball in the Z-direction (forward), that means that the goal line will be on the X-axis. So if you want your goalie to follow the ball and not go towards it or go up, you need to make your goalie follow the X-position of the ball. The Y and Z will always be the same, because the goalie will not go up or forward. So the goalie position will be something like this:
goalie.transform.position = new Vector3(ball.transform.position.x, goalie.transform.position.y, goalie.transform.position.z);
Now comes the net part, you don't want the goalie to follow the ball outside of the goal. It needs to stop at the goalposts. You could check the balls position against the goal position. So let's say the goal is at position 0,0,0 and the goal is 6 units wide. That means that you don't want the goalie to go over -3,0,0 or 3,0,0. This is something we can use in an if statement:
//If player is between the goalposts:
if( (player.transform.position.x > goal.transform.position.x - goalWidth / 2) && (player.transform.position.x < goal.transform.position.x + goalWidth / 2) )
{
//The ball is between the posts so follow the ball (Code above)
goalie.transform.position = new Vector3(ball.transform.position.x, goalie.transform.position.y, goalie.transform.position.z);
}
else
{
//The ball is outside of the goal so do nothing
//Or move back to the center of the goal
//Do something...
}