Синтаксис:
Используется csharp
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class RotationToMouse : MonoBehaviour
{
// в этот масиив в инспекторе перетаскиваю нужные спрайты, чтобы их порядок совпадал с массивом _derections
public Sprite[] sprites = new Sprite[0];
// Vector2.up, Vector2.one, Vector2.right, new Vector2(1,-1), Vector2.down, new Vector2(-1,-1), Vector2.left, new Vector2(-1,1)
// Vector2.up, Vector2.down, Vector2.left, Vector2.right
// new Vector2(1,1), new Vector2(1,-1), new Vector2(-1,-1), new Vector2(-1,1)
//new Vector2(0.4f,1), new Vector2(1,0.4f), new Vector2(1,-0.4f), new Vector2(0.4f,-1), new Vector2(-0.4f,-1), new Vector2(-1,-0.4f), new Vector2(-1,0.4f), new Vector2(-0.4f,1)
// массив сторон
private Vector2[] _directions = new Vector2[] {Vector2.up, Vector2.down, Vector2.left, Vector2.right};
// текущее направление
private Vector2 _currentDirection;
// сюда закешируем спрайтРендерер
private SpriteRenderer _spriteRend;
// при запуске игры кешируем спрайтРендерер
private void Start()
{
_spriteRend = GetComponent<SpriteRenderer>();
}
// постоянно обновляем направление и спрайт
void Update()
{
updateDirectionAndSprite();
}
private void updateDirectionAndSprite()
{
// временная переменная для обнаружения более близкого скалярного произведения
float maxDot = -1;
// направление от персонажа к курсору мыши
// перевод координаты персонажа в экранные координаты
Vector2 mouseToPlayerDirection = (Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position)).normalized;
Vector2 tempDirection = Vector2.zero;
// находим наиболее близкое направление из массива направлений к текущему направлению персонажа к курсору
foreach (Vector2 direction in _directions)
{
float currentDot = Vector2.Dot(mouseToPlayerDirection, direction);
if (currentDot > maxDot)
{
maxDot = currentDot;
tempDirection = direction;
}
}
// только если направление изменилось, то запоминаем это направление и меняем спрайт
if (_currentDirection != tempDirection)
{
_currentDirection = tempDirection;
_spriteRend.sprite = sprites[Array.IndexOf(_directions, _currentDirection)];
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class RotationToMouse : MonoBehaviour
{
// в этот масиив в инспекторе перетаскиваю нужные спрайты, чтобы их порядок совпадал с массивом _derections
public Sprite[] sprites = new Sprite[0];
// Vector2.up, Vector2.one, Vector2.right, new Vector2(1,-1), Vector2.down, new Vector2(-1,-1), Vector2.left, new Vector2(-1,1)
// Vector2.up, Vector2.down, Vector2.left, Vector2.right
// new Vector2(1,1), new Vector2(1,-1), new Vector2(-1,-1), new Vector2(-1,1)
//new Vector2(0.4f,1), new Vector2(1,0.4f), new Vector2(1,-0.4f), new Vector2(0.4f,-1), new Vector2(-0.4f,-1), new Vector2(-1,-0.4f), new Vector2(-1,0.4f), new Vector2(-0.4f,1)
// массив сторон
private Vector2[] _directions = new Vector2[] {Vector2.up, Vector2.down, Vector2.left, Vector2.right};
// текущее направление
private Vector2 _currentDirection;
// сюда закешируем спрайтРендерер
private SpriteRenderer _spriteRend;
// при запуске игры кешируем спрайтРендерер
private void Start()
{
_spriteRend = GetComponent<SpriteRenderer>();
}
// постоянно обновляем направление и спрайт
void Update()
{
updateDirectionAndSprite();
}
private void updateDirectionAndSprite()
{
// временная переменная для обнаружения более близкого скалярного произведения
float maxDot = -1;
// направление от персонажа к курсору мыши
// перевод координаты персонажа в экранные координаты
Vector2 mouseToPlayerDirection = (Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position)).normalized;
Vector2 tempDirection = Vector2.zero;
// находим наиболее близкое направление из массива направлений к текущему направлению персонажа к курсору
foreach (Vector2 direction in _directions)
{
float currentDot = Vector2.Dot(mouseToPlayerDirection, direction);
if (currentDot > maxDot)
{
maxDot = currentDot;
tempDirection = direction;
}
}
// только если направление изменилось, то запоминаем это направление и меняем спрайт
if (_currentDirection != tempDirection)
{
_currentDirection = tempDirection;
_spriteRend.sprite = sprites[Array.IndexOf(_directions, _currentDirection)];
}
}
}