hey guys!
i would like to have a tank-tower controll like in world of tanks. that means, you have a tower ontop of your tank which can rotate around the y-axis. and you have a gun that rotates with the tower and on the z-axis i think.
(pillar has the script and gun is the verticalObj and suspension the horizontal)
and here is my script:
using UnityEngine;
using System.Collections;
public class WeaponMover : MonoBehaviour
{
public Transform target;
public GameObject verticalRotateObj;
public GameObject horizontalRotateObj;
public float maxVerticalRotationSpeed = 2.0f;
public float maxHorizontalRotationSpeed = 1.0f;
public float maxVerticalRotation = 30.0f;
public float maxHorizontalRotation = 135.0f;
private Vector3 m_newHorEuler;
private Vector3 m_newVerEuler;
private Vector2 m_currPos;
private Vector2 m_targetPos;
private float m_conversion = 0.0f;
private float m_minVertAngle;
private float m_maxVertAngle;
private float m_minHorAngle;
private float m_maxHorAngle;
private float m_targetHorAngle;
private float m_targetVertAngle;
// Use this for initialization
void Start()
{
m_conversion = 180/Mathf.PI;
m_newHorEuler = Vector3.zero;
m_newVerEuler = Vector3.zero;
m_currPos = Vector2.zero;
m_targetPos = Vector2.zero;
}
// Update is called once per frame
void Update()
{
m_currPos.x = horizontalRotateObj.transform.position.x;
m_currPos.y = horizontalRotateObj.transform.position.z;
m_targetPos.x = target.transform.position.x;
m_targetPos.y = target.transform.position.z;
m_targetHorAngle = AngleToTarget(m_currPos, m_targetPos);
m_newHorEuler.y = m_targetHorAngle + 90.0f;
horizontalRotateObj.transform.eulerAngles = m_newHorEuler;
m_currPos.x = verticalRotateObj.transform.position.y;
m_currPos.y = verticalRotateObj.transform.position.x;
m_targetPos.x = target.transform.position.y;
m_targetPos.y = target.transform.position.x;
m_targetVertAngle = AngleToTarget(m_currPos, m_targetPos);
m_newVerEuler.z = m_targetVertAngle + 180.0f;
m_newVerEuler.y = m_newHorEuler.y;
verticalRotateObj.transform.eulerAngles = m_newVerEuler;
}
private float AngleToTarget(Vector2 objectPos, Vector2 targetPos)
{
return (Mathf.Atan2(objectPos.x - targetPos.x, objectPos.y - targetPos.y) * m_conversion);
}
}
works ok but the problem is, if the target moves over a certain line, the gun gets flipped 180° on z-axis. i have no idea why… ;(
every help is welcome!!!
update:
void Update()
{
Vector3 angle = Quaternion.LookRotation(target.position - horizontalRotateObj.transform.position).eulerAngles;
angle.x = horizontalRotateObj.transform.eulerAngles.x;
angle.z = horizontalRotateObj.transform.eulerAngles.z;
angle.y -= 90.0f;
horizontalRotateObj.transform.eulerAngles = angle;
angle = Quaternion.LookRotation(target.position - verticalRotateObj.transform.position).eulerAngles;
angle.x = verticalRotateObj.transform.eulerAngles.x;
angle.y -= 90.0f;
verticalRotateObj.transform.eulerAngles = angle;
}