How do I freeze X-Axis movement?

In my Pong-Clone I am able to get my enemy paddle to follow the ball’s movement on Y axis using a Vector3.MoveToward function but am unable to freeze it’s movement toward the ball on the X axis. The freeze X position button in the rigidbody component doesn’t work and this is probably due to the Vector3.MoveToward function being inside the void Update ().

Any suggestions?

using UnityEngine;
using System.Collections;
 
public class EnemyMove2Ball : MonoBehaviour {
 
    public Transform target; // drag the target (Ball) here
    float speed = 5.0f; // move speed
 
    void Update()
    {
       transform.position = Vector3.MoveTowards
         (rigidbody.position, 
          target.position, 
          speed*Time.deltaTime);       
    }
}

go to the rigidbody compnent of the gameobject and there u will find a property "constraints " just check the x axis. and your gameobject
x axis movement would be freeze

On line 14

//JS
    transform.position.x = 0;
//C#
transform.position = new Vector3(0f, transform.position.y, transform.position.z);

Freeze position in the editor only applies to physics. But you don’t use that, and probably should check isKinematic if you have not done that.

The example code is if the paddle is to be in a particular place on x axis.
You could also store the x location before moving it, and change transform.position.x back to what it should be afterwards.

That’s it. A non-kinematic Rigidbody should be moved by for example AddForce (and related) function. Then it will take your freeze-settings take into account. Also call this function preferably in the FixedUpdate() method. What you are doing is to directly manipulate the transform.position which is possible as well. In this case you could do the following in order to maintain the x-position.

Vector3 newPosition = Vector3.Lerp(transform.position, target.position, speed*Time.deltaTime);
transform.position = new Vector3(transform.position.x, newPosition.y, transform.position.z);

This way there would be no need for a Rigidboy and the z position is maintained as well.

Try this in your Update() function, so it only moves along y and z axis and having a x axis position value of ‘0’ for target Vector3;

void Update()
		{
				transform.position = Vector3.MoveTowards
				(transform.position, 
			 	 new Vector3(0, target.position.y,target.position.z), 
				 speed*Time.deltaTime);       
		}