Wondering if anyone can help me out here, I’m wanting to draw an image between two positions on the screen. I know I can change the scale of the image in the X axis to scale it between the two but I’m requiring that it’s accurate as well!
Many thanks!
I made something similar a while ago…
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class DisplayTextureBetweenTwoScreenPositions : MonoBehaviour
{
public Texture2D texture;
[Range(0.0f, 1.0f)]
public float xSize = 0.5f;
[Range(0.0f, 1.0f)]
public float ySize = 0.5f;
public bool maintainAspectRatio = false;
public bool pixelPerfect = false;
public Vector2 normalizedScreenPosA = Vector2.zero;
public Vector2 normalizedScreenPosB = Vector2.one;
public bool rotate = true;
private Vector3 screenPos;
private Rect rect;
private float angle;
private Vector2 GetSize()
{
int sizeX = Mathf.RoundToInt(xSize * (float)Screen.width);
int sizeY = maintainAspectRatio ? Mathf.RoundToInt((float)texture.height / (float)texture.width * (float)sizeX) : Mathf.RoundToInt(ySize * (float)Screen.height);
if (pixelPerfect)
{
sizeX = texture.width;
sizeY = texture.height;
}
return new Vector2(sizeX, sizeY);
}
void Update()
{
#if UNITY_EDITOR
if (texture != null)
{
#endif
Vector2 screenPosA = new Vector2(normalizedScreenPosA.x * Screen.width, normalizedScreenPosA.y * Screen.height);
Vector2 screenPosB = new Vector2(normalizedScreenPosB.x * Screen.width, normalizedScreenPosB.y * Screen.height);
Vector2 size = GetSize();
if (rotate)
{
Vector2 tmp = screenPosA - screenPosB;
angle = Mathf.Atan2(tmp.y, tmp.x) * Mathf.Rad2Deg;
}
Vector3 tmpScreenPos = Vector3.zero;
tmpScreenPos.x = (screenPosA.x + screenPosB.x) * 0.5f;
tmpScreenPos.y = (screenPosA.y + screenPosB.y) * 0.5f;
screenPos = tmpScreenPos;
Rect tmpRect = rect;
tmpRect.center = new Vector2(screenPos.x, Screen.height - screenPos.y);
tmpRect.width = size.x;
tmpRect.height = size.y;
rect = tmpRect;
#if UNITY_EDITOR
}
#endif
}
void OnGUI()
{
#if UNITY_EDITOR
if (texture != null)
{
#endif
if (rotate)
{
Matrix4x4 tmp = GUI.matrix;
GUIUtility.RotateAroundPivot(angle, rect.center);
GUI.DrawTexture(rect, texture);
GUI.matrix = tmp;
}
else
{
GUI.DrawTexture(rect, texture);
}
#if UNITY_EDITOR
}
#endif
}
}