using UnityEngine;
public class FollowMouseHorizontal : MonoBehaviour
{
private RectTransform rectTransform;
private Vector2 lastPosition;
public float speed = 5.0f;
void Start()
{
rectTransform = GetComponent<RectTransform>();
lastPosition = rectTransform.anchoredPosition;
}
void Update()
{
#if UNITY_EDITOR || UNITY_STANDALONE
HandleMouseInput();
#elif UNITY_IOS || UNITY_ANDROID
HandleTouchInput();
#endif
}
void HandleMouseInput()
{
Vector2 currentMousePosition = Input.mousePosition;
Debug.Log(Input.mousePosition);
MoveTowards(new Vector2(currentMousePosition.x, rectTransform.position.y));
}
void HandleTouchInput()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector2 currentTouchPosition = touch.position;
MoveTowards(new Vector2(currentTouchPosition.x, rectTransform.position.y));
}
}
void MoveTowards(Vector2 targetPosition)
{
Vector2 direction = targetPosition - (Vector2)rectTransform.position;
// 平滑移动
rectTransform.position = Vector2.Lerp(rectTransform.position, targetPosition, Time.deltaTime * speed);
// 改变UI物体的左右方向
if (direction.x > 0)
{
rectTransform.localScale = new Vector3(1, 1, 1); // 面向右
}
else if (direction.x < 0)
{
rectTransform.localScale = new Vector3(-1, 1, 1); // 面向左
}
}
}
Canvas 的 Render Mode 是Screen Space - Camera:
using UnityEngine;
public class FollowMouseHorizontalCmaera : MonoBehaviour
{
private RectTransform rectTransform;
public Camera uiCamera;
public float speed = 5.0f;
void Start()
{
rectTransform = GetComponent<RectTransform>();
}
void Update()
{
#if UNITY_EDITOR || UNITY_STANDALONE
HandleMouseInput();
#elif UNITY_IOS || UNITY_ANDROID
HandleTouchInput();
#endif
}
void HandleMouseInput()
{
Vector3 currentMousePosition = Input.mousePosition;
currentMousePosition.z = uiCamera.nearClipPlane; // 设置 z 值为相机的近剪切面
Vector3 worldMousePosition = uiCamera.ScreenToWorldPoint(currentMousePosition);
MoveTowards(new Vector2(worldMousePosition.x, rectTransform.position.y));
}
void HandleTouchInput()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector3 currentTouchPosition = touch.position;
currentTouchPosition.z = uiCamera.nearClipPlane; // 设置 z 值为相机的近剪切面
Vector3 worldTouchPosition = uiCamera.ScreenToWorldPoint(currentTouchPosition);
MoveTowards(new Vector2(worldTouchPosition.x, rectTransform.position.y));
}
}
void MoveTowards(Vector2 targetPosition)
{
Vector2 direction = targetPosition - (Vector2)rectTransform.position;
// 平滑移动
rectTransform.position = Vector2.Lerp(rectTransform.position, targetPosition, Time.deltaTime * speed);
// 改变UI物体的左右方向
if (direction.x > 0)
{
rectTransform.localScale = new Vector3(1, 1, 1); // 面向右
}
else if (direction.x < 0)
{
rectTransform.localScale = new Vector3(-1, 1, 1); // 面向左
}
}
}