Home > Enterprise >  How to match the y pos of an object with the y pos of another object?
How to match the y pos of an object with the y pos of another object?

Time:06-18

I have two gameObjects (pongBall, pongAI) and I want the "y position" of pongAI to always be the same as the "y position" of pongBall.

This is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class COMPLEXAI : MonoBehaviour
{
    void Update() {
        float x = pongAI.transform.position.x;
        float y = pongBall.transform.position.y;
        float z = pongAI.transform.position.z;
        pongAI.transform.position = new Vector3(x, y, z);
    }
}

Any ideas?

CodePudding user response:

I understand what you want to happen, however, I'm not quite sure what your issue is. Does your code not work as expected? If so, how is the behavior different from what it is supposed to do?

I think you have it almost right. In your code snippet you seem to miss members for pongAi and pongBall, so you can't assign them to your script. If you add the script as component to your pongAI GameObject, you actually only need a member for pongBall:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class COMPLEXAI : MonoBehaviour
{
    public Transform pongBall;

    void Update() {
        float x = transform.position.x;
        float y = pongBall.position.y;
        float z = transform.position.z;

        pongAI.transform.position = new Vector3(x, y, z);
    }
}

This should work as intended, if you add the script as component to your pongAi GameObject in the Unity Editor, and assign the pongBall GameObject to the pongBall field in said component. Hope this helps!

  • Related