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
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;
}
}
}