- Home /
Making an enemy fly towards Object and then around it until it's destroyed
Hello all!
I am still making my SpaceShip game and I have hit another wall.
I want to make an enemy ship fly towards a GameObject, and when it reaches it, then it should start rotating around that gameobject until it is destroyed.
I have my enemy fly towards target but I have no idea to witch it to fly around that gameobject :)
Any help will be appreciated.
Thanks!
So i started like this
public GameObject target;
public float speed;
float GetAngleToTarget()
{
Vector3 v3 = target.transform.position - transform.position;
return Mathf.Atan2 (v3.y, v3.x) * Mathf.Rad2Deg;
}
if(EnemyMovementType == 2)
{
targetAngle = GetAngleToTarget();
}
Answer by toromano · Oct 28, 2015 at 10:15 AM
I would recommend using two rigidbodies(for enemy and target) and a distance joint. First i would set a velocity for gameobject to enter the area. After the gameobject is in the area (in trigger), i would set a distance joint between enemy and target. Something like:
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
public Transform target;
private Transform thisTransform;
private Rigidbody2D rgbody;
public float radius = 5.0f;
private bool connected = false;
private DistanceJoint2D joint;
public float InitialVelocity = 5.0f;
// Use this for initialization
void Start () {
thisTransform = transform;
rgbody = gameObject.GetComponent<Rigidbody2D>();
if(target != null)
{
var fromGOtoTargetVec = target.position - thisTransform.position;
var fromTargetToTangent = Quaternion.AngleAxis(90.0f, Vector3.up) * fromGOtoTargetVec.normalized * radius;
rgbody.velocity = (target.position + fromTargetToTangent - thisTransform.position).normalized * InitialVelocity;
}
}
// Update is called once per frame
void FixedUpdate () {
if(connected)
{
joint.distance -= .001f * Time.fixedDeltaTime; //modify this value
}
}
void OntriggerStay(Collider other)
{
var otherRB = other.GetComponent<Rigidbody2D>();
if(otherRB != null && !connected && (other.transform.position - thisTransform.position).magnitude < radius)
{
joint = gameObject.AddComponent<DistanceJoint2D>();
joint.connectedBody = rgbody;
joint.distance = radius;
connected = true;
}
}
}
You should set target Sphere collider as trigger.
Thank you, that is very interesting - I never used a joint before, so now I will try. Thanks a lot for your help.