Hello Unity community, I’m currently developing a game where you play as an air traffic controller trying to crash planes. You move planes by clicking on them then clicking on the map for where they should go. However, I have encountered a problem. Whenever I click on a plane It sets the target position the same for all the planes, Is there any way I can make it so it only changes it for the plane I have selected? Or maybe is there any other way I can approach this?
Here is my code for the plane logic
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlaneMovement : MonoBehaviour
{
[Header("References")]
[SerializeField] private Transform targetPosition;
[Header("Attributes")]
[SerializeField] private float planeSpeed = 5f;
[SerializeField] private float stoppingDistance = 0.1f;
private Rigidbody2D rb2d;
private bool isPlaneSelected = false;
private void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (isPlaneSelected)
{
SetPlaneTarget();
}
else
{
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if(hit.collider != null && hit.collider.CompareTag("Plane"))
{
SelectPlane();
}
}
}
//Movement logic goes here :
Vector3 direction = (targetPosition.position - transform.position).normalized;
rb2d.velocity = direction * planeSpeed;
float distance = Vector3.Distance(transform.position, targetPosition.position);
if (distance <= stoppingDistance)
{
rb2d.velocity = Vector3.zero;
}
//Rotation logic goes here :
transform.up = direction;
}
private void SelectPlane()
{
if(isPlaneSelected)
{
DeselectPlane();
}
isPlaneSelected = true;
}
private void SetPlaneTarget()
{
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = -Camera.main.transform.position.z;
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(mousePosition);
worldPosition.z = 0f;
targetPosition.position = worldPosition;
isPlaneSelected = false;
}
private void DeselectAllPlanes()
{
PlaneMovement[] allPlanes = FindObjectsOfType<PlaneMovement>();
foreach(PlaneMovement plane in allPlanes)
{
plane.DeselectPlane();
}
}
private void DeselectPlane()
{
isPlaneSelected = false;
}
private void OnDrawGizmos()
{
Gizmos.DrawLine(transform.position, targetPosition.position);
}
}
You can see in the images below that whenever I click on a plane and then on the map It changes the target position for both planes