Daniel Lip
Daniel Lip

Reputation: 11341

Why the cannon is never rotating facing at the target?

What I want is to make some ai that the cannon/turret will rotate automatic facing the target. But when I'm running the game and moving the target in the scene view window the cannon is facing the other direction and not to the target.

The script to rotate:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateTurret : MonoBehaviour
{
    [SerializeField]
    private float turnRateRadians = 2 * Mathf.PI;

    [SerializeField]
    private Transform turretTop; // the gun part that rotates

    [SerializeField]
    private Transform bulletSpawnPoint;

    [SerializeField]
    public GameObject target;

    void Update()
    {

        TargetEnemy();
    }

    void TargetEnemy()
    {
        if (target != null)
        {
            Vector3 targetDir = target.transform.position - transform.position;
            // Rotating in 2D Plane...
            targetDir.y = 0.0f;
            targetDir = targetDir.normalized;

            Vector3 currentDir = turretTop.forward;

            currentDir = Vector3.RotateTowards(currentDir, targetDir, turnRateRadians * Time.deltaTime, 1.0f);

            Quaternion qDir = new Quaternion();
            qDir.SetLookRotation(currentDir, Vector3.up);
            turretTop.rotation = qDir;
        }
    }
}

And this is a screenshot showing where the script is attached to and when I'm moving with them ouse in the scene view the target the cube backward and forward not yet around the cannon the cannon is always facing the other direction:

Turret

And this is when running the game right after the game is running the turret automatic facing the other way and when moving the target the cube the turret will keep rotating facing the other direction:

Turret

Upvotes: 0

Views: 154

Answers (1)

Andrew Hartz
Andrew Hartz

Reputation: 133

I think turretTop.forward represents the positive z dirrection of your model's local coordinates, but your barrel is alligned to the x-axis of the model. Maybe if you replaced:

Vector3 currentDir = turretTop.forward;

with:

Vector3 currentDir = turretTop.right;

Upvotes: 3

Related Questions