- Home /
Rotating GUI Texture By Angle
So I used Ben Pitt's code from this post: http://answers.unity3d.com/questions/11022/how-to-rotate-gui-textures.html to get the rotation part working. Now what I need is for the texture to always point toward a game object in the scene, I'm not sure how to do this, I've tried a few things that didn't work. Any ideas?
Answer by Scribe · Nov 04, 2012 at 11:54 AM
Hopefully this works for you, unfortunately I can only really read C# and can't write it so easily so I've written this in unityscript, but maybe you can convert the additions I've made, or possibly unityscript is fine for you...
var texture : Texture2D = null;
var angle : float = 0;
var size : Vector2 = new Vector2(128, 128);
var pos : Vector2 = new Vector2(0, 0);
var rect : Rect;
var pivot : Vector2;
var targetObj : GameObject;
var screenPos : Vector2;
var offset : Vector2;
var Rads : float = 0;
function Start() {
UpdateSettings();
}
function Update() {
screenPos = Camera.main.WorldToScreenPoint(targetObj.transform.position);
screenPos.y = Screen.height-screenPos.y;
offset = screenPos - pos;
Rads = Mathf.Atan2(offset.y, offset.x)-(Mathf.PI/2);
RadDegConvert(Rads);
}
function UpdateSettings() {
pos = new Vector2(transform.localPosition.x, transform.localPosition.y);
rect = new Rect(pos.x - size.x * 0.5f, pos.y - size.y * 0.5f, size.x, size.y);
pivot = new Vector2(rect.xMin + rect.width * 0.5f, rect.yMin + rect.height * 0.5f);
}
function OnGUI() {
if (Application.isEditor) { UpdateSettings(); }
var matrixBackup : Matrix4x4 = GUI.matrix;
GUIUtility.RotateAroundPivot(angle, pivot);
GUI.DrawTexture(rect, texture);
GUI.matrix = matrixBackup;
}
function RadDegConvert(radians) {
angle = radians*360/(Mathf.PI*2);
}
hope that works for you,
Scribe
Unityscript is perfect because that's what I converted the code to anyways.
Answer by Chimera3D · Nov 05, 2012 at 05:08 AM
Your code worked perfectly except for one part... it was inverted. To fix that I added the lines `pos.y = Screen.height - pos.y`; and `screenPos.y = Screen.height - screenPos.y; before you calculate the offset. This is something I found out about very recently. Thanks!
Glad you got it to work, and thanks for pointing that out! I'll know for next time :D