Saturday, 18 July 2015

Unity Automated Turret Tutorial Tracking Code

Unity Automated Turret Tutorial Tracking Code

A video explainging this code is available here: https://www.youtube.com/watch?v=-_k8Ob7ElUo&feature=youtu.be

I have provided two scripts below. Once is for a simple tracking system in unity & the other is just to move an object continuously between two points. Remember to name the file the same as the class name or they won't compile in unity.

Tracking Script:

using UnityEngine;
using System.Collections;

public class TrackingSystem : MonoBehaviour {
public float speed = 3.0f;
public GameObject m_target = null;
Vector3 m_lastKnownPosition = Vector3.zero;
Quaternion m_lookAtRotation;

// Update is called once per frame
void Update () {
if(m_target){
if(m_lastKnownPosition != m_target.transform.position){
m_lastKnownPosition = m_target.transform.position;
m_lookAtRotation = Quaternion.LookRotation(m_lastKnownPosition - transform.position);
}

if(transform.rotation != m_lookAtRotation){
transform.rotation = Quaternion.RotateTowards(transform.rotation, m_lookAtRotation, speed * Time.deltaTime);
}
}
}

bool SetTarget(GameObject target){
if(!target){
return false;
}

m_target = target;

return true;
}
}


Movement Script:

using UnityEngine;
using System.Collections;

public class EnemyAi : MonoBehaviour {
public Transform pointA;
public Transform pointB;
public float speed;

// Update is called once per frame
void Update () {
transform.position = Vector3.Lerp(pointA.position, pointB.position, Mathf.Sin(Time.time * speed));
}
}

No comments:

Post a Comment