Created
October 4, 2017 10:46
-
-
Save dimmduh/cd22c88ad53e99df0a625508f49e1954 to your computer and use it in GitHub Desktop.
Unity tank rotation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class Tank : MonoBehaviour | |
{ | |
public Transform cabina; | |
public Transform dulo; | |
public Transform target; | |
// Update is called once per frame | |
void Update () | |
{ | |
var angleY = Mathf.Rad2Deg * AngleInRadXZ(cabina.position, target.position); | |
var h = target.position.y - dulo.position.y; | |
var v1 = new Vector2(dulo.position.x, dulo.position.z); | |
var v2 = new Vector2(target.position.x, target.position.z); | |
var m = (v1 - v2).magnitude; | |
var a = 0f; | |
if (Math.Abs(m) > 0.01f) | |
a = Mathf.Asin(h / m); | |
cabina.rotation = Quaternion.Euler(cabina.rotation.eulerAngles.x, angleY, cabina.rotation.eulerAngles.x); | |
dulo.localEulerAngles = new Vector3(0,0, a * Mathf.Rad2Deg); | |
} | |
public static float AngleInRadXZ(Vector3 vec1, Vector3 vec2) | |
{ | |
return Mathf.Atan2( vec2.x - vec1.x, vec2.z - vec1.z) - Mathf.PI * 0.5f; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment