How to freeze movement on X-axis. (See Comments for Update)

I’m putting the finishing touches on my Pong clone but I am unable to change the enemy’s speed once I set him to follow the ball’s position.Y

First things first, im trying to get it to listen to the speed variable change

Second I’m looking for a point in the right direction as far as getting the enemy to change his speed depending on the speed of the ball.

Here’s my code: C#

``````using UnityEngine;
using System.Collections;

public class NewEnemyAI : MonoBehaviour
{
public float yMin, yMax;
public Transform target;
public float speed;

void Update ()
{
float inputSpeed = Input.GetAxisRaw ("Vertical");

transform.position += new Vector3 (0, inputSpeed * speed * Time.deltaTime, 0);
}

void FixedUpdate ()
{
rigidbody.position = new Vector3
(8.0f,
Mathf.Clamp (target.position.y, yMin, yMax),
1.0f);
}
}
``````

I think that in the Start function you should define your “speed” variable to be the velocity of the ball. Something like:

speed = GameObject.Find(“ball”).velocity

Then the variable would be a reference… I think… to the ball’s velocity. If I’m wrong and that line only fetches the current value, then you could have a reference like:

GameObject ball;

Then in Start:

ball = GameObject.Find(“ball”)

And then whenever you need it, reference “ball.velocity” which is a Vector3.

So i ended up using a vector3.movetowards method and its working great except I cannot get the enemy paddle to freeze on the X-Axis. I tried clicking the freeze X position in the rigidbody component but since my code is in the update function it overrides it I guess. Any help on code for freezing X-Axis movement in the update function?

``````using UnityEngine;
using System.Collections;

public class EnemyMove2Ball : MonoBehaviour {

public Transform target; // drag the player here
float speed = 5.0f; // move speed

void Update()
{
transform.position = Vector3.MoveTowards
(rigidbody.position,
target.position,
speed*Time.deltaTime);

}
}
``````