[Solved] Constraint and Freeze movement on Y Axis?

I tried to freeze object with rigidbody constraints on Y axis but was ignored. Is it because the script below is not physics driven? Can someone please tell me how I can ignore Y axis on the script below? Thank you!

using UnityEngine;
using System.Collections;

public class FollowScript : MonoBehaviour {
   
    //The target player
    public Transform player;
    //At what distance will the enemy walk towards the player?
    public float walkingDistance = 10.0f;
    //In what time will the enemy complete the journey between its position and the players position
    public float smoothTime = 10.0f;
    //Vector3 used to store the velocity of the enemy
    private Vector3 smoothVelocity = Vector3.zero;

    //Call every frame
    void Update()
    {
        //Look at the player
        transform.LookAt(player);
        //Calculate distance between player
        float distance = Vector3.Distance(transform.position, player.position);
        //If the distance is smaller than the walkingDistance
        if(distance < walkingDistance)
        {
            //Move the enemy towards the player with smoothdamp
            transform.position = Vector3.SmoothDamp(transform.position, player.position, ref smoothVelocity, smoothTime);


        }
    }
}

That’s correct… constraints prevent the physics from affecting certain axes

Is there a way to do it without using physics? with the script above?

Yeah for sure. There’s more than one way to do it, but an easy way:

transform.position = Vector3.SmoothDamp(transform.position, new Vector3(player.position.x, transform.position.y, player.position.z), ref smoothVelocity, smoothTime);

That should work, I think… basically you’re setting 2 axes to your new spot, and keeping the y axis the same as before. This line is the same as your line 26 above, but with player.position replaced with:
new Vector3(player.position.x, transform.position.y, player.position.z)

3 Likes

yup that did the trick thank you :smile:

No problem!