Created
October 30, 2019 23:59
-
-
Save mzandvliet/7a0d95397709f606c6b8dd6645be730a to your computer and use it in GitHub Desktop.
Rotating A Thing To Look At Another Thing, Without Trigonometry - Part 1
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 UnityEngine; | |
using Unity.Mathematics; | |
public struct Transform2D { | |
public float2 position; | |
public float2 velocity; | |
} | |
public class LookAt2dWithoutTrig : MonoBehaviour | |
{ | |
[SerializeField] private Camera _camera; | |
private Transform2D a; // shoot ray from here | |
private Transform2D b; // to here | |
private float2 ray; | |
private void Update() { | |
var aScreen = (float3)_camera.ScreenToViewportPoint(new Vector3(Screen.width / 2f, Screen.height / 2f, 0f)); | |
var bScreen = (float3)_camera.ScreenToViewportPoint(Input.mousePosition); | |
a.position = aScreen.xy; | |
b.position = bScreen.xy; | |
float2 delta = b.position - a.position; | |
float2 deltaNormal = math.normalize(delta); | |
ray = cmul(deltaNormal, new float2(1, 0)); | |
} | |
private void OnDrawGizmos() { | |
Gizmos.color = Color.white; | |
Gizmos.DrawLine(new float3(a.position, 0), new float3(a.position + ray, 0f)); | |
Gizmos.color = Color.red; | |
Gizmos.DrawSphere(new float3(a.position, 0), 0.025f); | |
Gizmos.DrawSphere(new float3(b.position, 0), 0.025f); | |
} | |
// Complex number multiplication | |
private static float2 cmul(float2 a, float2 b) { | |
return new float2( | |
a.x * b.x - a.y * b.y, | |
a.x * b.y + a.y * b.x | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment