Rotate 90 degrees when within x range

Hi everyone, new here (and relatively new to Unity).

I’m trying to figure out how I would rotate my gameobject when it gets within a certain range. I am creating a top down 2D ship combat game, and when the ship gets within a certain distance, I want to rotate it as if it were going to shoot from the sides, and then rotate back when its no longer in attack range.

I’ve set it up currently as follows, but everything I try by changing rotation in a different script ends up with strange results, so I assume I need to do something to the AIPath script, I just don’t know where to start. Again, sorry for the messy code, I’m still learning:

public bool isProvoked = false;
    public Transform target;

    [SerializeField] float chaseRange = 5f;
    [SerializeField] float disengageRange = 20f;
    [SerializeField] float attackRange = 5f;

    private AIPath aiPath;
    private AIDestinationSetter aIDestinationSetter;

    void Start()
    {
        aIDestinationSetter = GetComponent<AIDestinationSetter>();
        aiPath = GetComponent<AIPath>();
        target = aIDestinationSetter.target;
    }

    void Update() {
        distanceToTarget = Vector2.Distance(target.position, transform.position);
        if (distanceToTarget <= chaseRange) { 
            isProvoked = true;
        }
        if (distanceToTarget >= disengageRange) {
            isProvoked = false;
        }
        if (isProvoked == true) {
            EngageTarget();
        }
        
        if (isProvoked == false) {
            DisengageTarget();
        }
    }

    private void EngageTarget() {
        aiPath.canMove = true;
        if (distanceToTarget <= attackRange) {
            AttackTarget();
        }
        else {
            StopAttacking();
        }
    }

    private void AttackTarget() {
        //Rotate Enemy Here
        //Enemy Attacks Here
    }

    private void StopAttacking() {
        //Rotate Back to Original Rotation Here
        //Stop Attacking Here
    }

    private void DisengageTarget() {
        aiPath.canMove = false;
    }

Any help is appreciated - thanks!

Hi

You can make the movement script not rotate the object itself by setting ai.updateRotation = false. Then you can access the desired rotation of the ai in ai.rotation and use that to set your Transform’s rotation as desired.

That worked perfectly, thank you!

I’m actually trying to do the same thing but add a rigidbody2d force to my object. I used ai.updateposition = false, thinking that’d I would be able to do the same thing, but using rigidbody2d.addforce() didn’t actually move the object.

Is there something else I need to do here other than turn off updateposition? Can I use rigidbody force with A* or do I need to update the transform.position?

Thanks again!

1 Like