- Home /
Scripting for AI
I'm making a pong clone and having trouble scripting for the opponent. I'm trying to use transform.Translate and ball.transform.right to get it to move, but right now it only goes to the right, then gets stopped by the boundary of the playing field. Here is the script I am currently using:
using UnityEngine; using System.Collections;
public class AI : MonoBehaviour
{
public GameObject ball; public float speed;
void FixedUpdate ()
{
transform.Translate (ball.transform.right * speed * Time.deltaTime);
}
}
How do I fix this?
I only want it to move to the ball's position on the x axis.
Answer by Aridez · Mar 11, 2014 at 11:16 PM
You can actually do this editing the transform.position directly: // i guess that the ball.transform.right thing is the actual x axis position
if (ball.transform.right > transform.position.x) {
rigidbody2d.velocity = new Vector2 (speed, 0);
} else if (ball.transform.right < transform.position.x) {
rigidbody2d.velocity = new Vector2 (speed*-1f, 0);
}
I think you can do something like that (i think the code is not 100% correct but the basic idea is to attach a rigidbody that will only move on the x axis using the velocity).
Your answer
Follow this Question
Related Questions
simple 2d car Ai 0 Answers
Transform.translate change 1 Answer
My FOV for enemy script is not working 2 Answers
Move RigidBody with translate 1 Answer
The floating point origin and AI 1 Answer