Kind of new to Unity3D and C# programming in general. I’m trying to write an AI opponent for a Pong game I’m making, and I’d like to make it so that the paddle begins to move as soon as it detects that the ball has been returned by the player and is headed toward it. Is there a boolean function or some other function that I could use?
At the moment, my AI paddle will only move once it detects that the position of the ball is within its part of the playing field. This results in some jittery movement and sudden stops (once it’s out of the area) that I’m not liking.
using UnityEngine;
using System.Collections;
public class EnemyController : MonoBehaviour {
private int speed = 7;
private Transform ball;
private float minY = -4.75f;
private float maxY = 4.75f;
void Update() {
if (GameObject.FindWithTag("Ball")) {
ball = GameObject.FindWithTag("Ball").transform;
Vector3 pos = transform.position;
if (ball.position.x > 0) {
pos.y = Mathf.Lerp(pos.y, ball.position.y, speed * Time.deltaTime);
transform.position = pos;
}
}
}
}
Consider the direction of the pad, let’s say it is the right paddle looking to the left. So, the direction is leftward (Vector3.left could be depending on your game orientation).
Using:
float dot = Vector3.Dot(ball.movement.normalized, paddle.direction.normalized);
if(dot < 1 ){
// Ball is coming towards paddle
}
dot product compares two vectors, if they are aligned, you get 1, if they are opposite you get -1, if they are 90 degrees you get 0. This is based on cosin, if you know your trig, you know what I mean.
Given you’re writing pong, I’m assuming its a fairly simple situation in which the AI is on 1 side of the screen, and the player is on the other.
On that basis it’s very simple - you just need to look at which direction the ball is moving. If you are using the normal 3D unity physics engine, and your ball has a rigid body, you could see if your ball is moving left or right:
if(ball.rigidBody.velocity.x < 0)
{
//ball is moving left
}
else
{
//ball is moving right
}
If you’re using the 2D physics engine, just replace ball.rigidBody with ball.rigidBody2D.
If your paddles are at the top and bottom of the screen (not right and left) then you’ll want to look at the y component of the velocity, not the x, so you can find out if the ball is moving up/down instead of right/left.