I’m am trying to make a animation for a turret and i want the turret to look at the enemy but i can’t do both.This is my code. Help me please.
using UnityEngine;
using System.Collections;
public class Gun1 : MonoBehaviour {
public Transform enemy;
public Transform turret;
public Animation anim;
void Start () {
turret.Rotate (transform.rotation.x+20,transform.rotation.y+90,transform.rotation.z);
anim = GetComponentInParent<Animation>();
}
void Update () {
}
void OnTriggerEnter(Collider objTriggered){
if (!anim.isPlaying) {
anim.Play();
}
}
void OnTriggerStay(Collider objTriggered){
if (objTriggered.transform.parent.name == "Enemy") {
var rotate = Quaternion.LookRotation (enemy.position - turret.position);
turret.rotation = Quaternion.Slerp (turret.rotation, rotate, Time.deltaTime * 5.0f);
}
}
void OnTriggerExit(Collider objTriggered){
if (anim.isPlaying) {
anim.Stop();
}
}
}
var LookAtTarget : Transform;
var rotate;
var rotationDampening = 2.0;
var range = 50.0;
var distanceToPlayer;
var hit : RaycastHit;
var forward;
public var ionBallPrefab : Rigidbody;
public var ionCannonEnd : Transform;
var ionCannon : AudioClip;
var cannonReady : boolean = true;
function Awake()
{
LookAtTarget = GameObject.FindWithTag("Player").GetComponent(Transform);
}
function Update()
{
forward = transform.TransformDirection(Vector3.forward);
distanceToPlayer = Vector3.Distance(LookAtTarget.position, transform.position);
{
if(distanceToPlayer <= range) // Check to see if player/Target is within range
{
if(LookAtTarget)
{
rotate = Quaternion.LookRotation(LookAtTarget.position - transform.position);
}
if(Physics.Raycast(transform.position, forward, hit, range))
//Debug.Log( hit.collider.gameObject.name ); // what did the ray hit??
if(hit.collider.gameObject.tag == "Player") //Shoot at Player
if(cannonReady == true)
Shoot(); //Perform Shoot function
}
else
rotate = Quaternion.identity;
transform.rotation = Quaternion.Slerp(transform.rotation,rotate,Time.deltaTime *
rotationDampening);
}
}
function Shoot()
{
// DO YOUR STUFF HERE
}
It will rotate your turret to follow any object with the tag ‘Player’
You can set turn speed, tracking distance etc.
have fun
edit -
as @joe I don’t think its possible to control it during an animation.
Best other suggestion that comes to mind is split up the parts.
Allow the lower section to be moved via animation and the upper sections movement/direction to be handled by script.
Of course, the animation controls the Transform component, hence making it impossible to control them “while” the animation is playing.
The best approach is to put the Object that is being animated in an Empty gameObject (call is Parent), and to Control that parent, that way the object will animate and the parent will be available for you to control!