Making an object follow another object C#
Hello everyone, I am trying to make an object follow another object after colliding with it. First I tried making the object move towards it (towards its position) but that didn't work. Instead, I decided to switch the gameobject from one parent to another (the second parent being the object I want it following). So it works perfectly except when I want the object to switch back to its original parent it only works 50% of the time. It's very odd. Sometimes it will work great but other times it will not switch parents. The code I'm sure looks messy but that's because I have been trying many different things for it to work. In case your wondering its a capture the flag game and I want the flag to follow the person. Thanks! This is the code: using UnityEngine; using System.Collections; public class PlayerMovement : MonoBehaviour { public GameObject BluePlayer; public GameObject target;
public GameObject RedFlagParent;
private Transform tempTrans;
public GameObject RedPlayer;
public GameObject RedFlag;
public GameObject BlueFlag;
public GameObject BlueX;
public GameObject RedX;
public Transform TeleportLocationBlue;
public Transform TeleportLocationRed;
public Transform TeleportLocationRedFlag;
public Transform RedPlayerTransform;
public Transform RedFlagTransform;
public float moveSpeed = 05f;
public VJHandler jsMovement;
private Vector3 direction;
private float xMin, xMax, yMin, yMax;
void Start()
{
//Initialization of boundaries, used to be 50
xMax = Screen.width - 15;
xMin = 15;
yMax = Screen.height - 15;
yMin = 15;
}
void Update()
{
//RedFlag.transform.position = Vector2.MoveTowards(transform.position, BluePlayer.transform.position, 2f);
direction = jsMovement.InputDirection; //InputDirection can be used as per the need of your project
if (direction.magnitude != 0)
{
transform.position += direction * moveSpeed;
transform.position = new Vector3(Mathf.Clamp(transform.position.x, xMin, xMax), Mathf.Clamp(transform.position.y, yMin, yMax), 0f);//to restric movement of player
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "BLUEPLAYER")
{
if (BlueX.transform.position.x <= 394)
{
BluePlayer.transform.position = TeleportLocationBlue.transform.position;
//RedFlag.transform.position = Vector3.MoveTowards(RedFlag.transform.position, BluePlayer.transform.position, 0.3f);
Debug.Log("HIT");
}
else if (BlueX.transform.position.x >= 394)
{
RedFlag.transform.SetParent(RedFlagTransform.transform, true);
RedFlag.transform.position = new Vector3(730, 262, 1);
RedPlayer.transform.position = TeleportLocationRed.transform.position;
Debug.Log("Not Hit");
}
}
if (collision.tag == "RedFlag")
{
RedFlag.transform.SetParent(RedPlayerTransform.transform, true);
Debug.Log("Flag Hit");
}
}
}