Compare position of 2 objects

Hi, I have a turret and would like it to shoot a shot towards the player IF the player stands on the same height as it does.
This is my code for comparing the position on the Y of the 2 object, somehow the first if never ran (if I understand correctly throguh my debug.log)

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

public class Raycast : MonoBehaviour {

	Vector2 directionRay;
	public GameObject Player;
	private float playerPosY;
	private float playerPosX;
	private SpriteRenderer spriteRenderer;

	// Use this for initialization
	void Start () {
		spriteRenderer = GetComponent<SpriteRenderer> ();
	}
	
	// Update is called once per frame
	void Update () {
		ComparePositionY();
		RaycastHit2D Hit = Physics2D.Raycast (transform.position, directionRay);
		Debug.Log ("Direction x =" + directionRay.x);
		Debug.Log ("Direction y =" + directionRay.y);
		if (Hit.collider == Player) 
		{
			Debug.Log ("I hit the player");
		}
	}

	void ComparePositionY () {
		playerPosY = Player.transform.position.y;
		playerPosX = Player.transform.position.x;
	
		if (transform.position.y == playerPosY)
		{
			Debug.Log ("PosX =" + transform.position.x);
			if (transform.position.x > playerPosX)
			{
				Debug.Log ("PlayerPosX " + playerPosX);
				spriteRenderer.flipX = true;
				directionRay = new Vector2 (-1, 0);
			}
			if (transform.position.x < playerPosX)
			{
				Debug.Log("PlayerPosY " + playerPosY);
				directionRay = new Vector2 (1, 0);
			}
		}
	}
}

Can anyone tell me what I did wrong? I did let the player jump around the object so that the turret’s position and the player’s position can have a moment equal to each other but it still doesn’t work.

“if (transform.position.y == playerPosY)”

^ this is likely the problem.

A float is never going to be equal to another float unless they were explicitly set (for instance, x = 10f, y = 10f) before comparing. Even just adding and subtracting whole numbers can end up with tiny differences over time and they won’t equate anymore, just because of the nature of floats to be efficient more than 100% accurate.

Just remove that line completely and it should work.

I would also just do “else” for the second X direction check- as I said, floats aren’t going to be equal, so if the X position of the player isn’t greater than the X position of the turret, then it’s definitely less than- no need to for the second check there.

Vector3.MoveTowards is your friend . If you want to compare two objects then you should do it something like this

void Update(){
transform.position = Vector3.MoveTowards(transform.position, destination, Time.deltaTime * speed);
    if(Vector3.Distance(transform.position, destination) < .001f) {
        Debug.Log("The distance between the object is :" + transform.position);
    }
}

Hope that helps you . And please bare in mind that comparing two floats without setting them is very wrong :slight_smile: Happy coding