Ethan Pelton
Ethan Pelton

Reputation: 1796

Unity movement near point

I have spaceships that chase each other. They currently move to their target exactly, but I want to replicate physics you might see on water or in zero gravity, where the object would overshoot its target, turn and move back toward it. Possibly hovering around the target back and forth. I've tried addforce and addrelativeforce, and velocity, but those don't seem to give me the desired effect. Any ideas?

This is my code...

Vector3 dir = (new Vector3(x, y, 0) - transform.parent.position).normalized;
        float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
        float heading = Mathf.Atan2(dir.x, dir.y);
        transform.parent.rotation = Quaternion.Slerp(transform.parent.rotation, Quaternion.Inverse(Quaternion.Euler(0f, 0f, heading * Mathf.Rad2Deg)), Time.deltaTime * 12f);
        //transform.parent.position += dir * speed * Time.deltaTime;
        //rb.AddForce(dir);
        rb.velocity = new Vector3(dir.x * speed, dir.y * speed, 0);

Upvotes: 1

Views: 101

Answers (1)

Fredrik
Fredrik

Reputation: 5108

Here's how I achieve that AI in a 2D space shooter:

void FixedUpdate()
{
    var target = Player != null ? PlayerObject : Target; // If player is dead, go for secondary target
    Vector2 dir = -(Vector2)(transform.position - target.transform.position + targetOffset); // Direction

    // dir.magnitude is the distance to target
    if (dir.magnitude > reaction * rangeModifier) // If I'm far away from the target, slowly rotate towards it
    { 
        // calculate angle toward target and slowly rotate child ship object toward it in the speed of turnRate
        float attackAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90;
        ship.transform.rotation = Quaternion.Slerp(ship.transform.rotation, Quaternion.AngleAxis(attackAngle, Vector3.forward), turnRate * Time.deltaTime);
    }
    else // If I'm close to the target just keep going straight ahead and fire until I'm too far away again
    {
        My.weapon.Shoot(dir);
    }


    _rb.velocity = ship.transform.up.normalized * My.Movementspeed; // Add velocity in the direction of the ship's rotation
}

This will give you an AI that goes in eight (8) shapes around the target. If you have many objects running this code I recommend adding a random offset to the target, to simulate swarming and more realistic flight aim.

I added comments to explain some details of the code.

Upvotes: 1

Related Questions