Хочу менять спрайт персонажа в зависимости от позиции курсора на экране Unity 2D
Хотел сделать, чтобы при нажатии и удерживании правой кнопки мыши персонаж менял свой спрайт на "готов к стрельбе" (2D, вид сбоку), и чтобы показываемый спрайт зависел от положения курсора мыши на экране. Друг скинул мне кусок кода, я его интегрировал, получилось как-то так, вставил нужные спрайты в юнити, но ничего не поменялось. Вместо спрайтов при нажатии ПКМ ничего не происходит, скрипт стрельбы работает, но воспроизводится стандартная анимация с аниматора. Помогите с решением проблемы, ибо сам мало разбираюсь, начинающий.
Вот мой код:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
public class weapon : MonoBehaviour
{
public Transform FirePoint;
public Transform FirePoint_2;
public GameObject BulletPrefab;
public Vector2 lookDirection;
public float lookAngle;
public Rigidbody2D rb;
//public Animator animator;
bool scope = false;
[Header("Add sprites in counter-clockwise order starting with east")]
// array of sprites added in the inspector
public Sprite[] directionSprites;
// references to components
public SpriteRenderer _spriteRenderer;
public Camera _mainCamera;
// called once when this component is first created
public void Awake()
{
// get the SpriteRenderer component on this GameObject.
// This can return null if there isn't one,
// but we know there is one because of RequireComponent
_spriteRenderer = GetComponent<SpriteRenderer>();
// get the main camera in the scene
_mainCamera = Camera.main;
}
// Update is called once per frame
void Update()
{
var dir =Camera.main.ScreenToWorldPoint( Input.mousePosition)-FirePoint.transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg -90f;
FirePoint.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
//animator.SetBool("IsScoped", scope);
if (Input.GetButtonDown("Fire2"))
{
scope = true;
}
else if (Input.GetButtonUp("Fire2"))
{
scope = false;
}
if (scope==true)
{
// get the current direction
Vector2 directionTowardsMouse = GetDirectionTowardsMouse();
// update the sprite
UpdateSpriteDirection(directionTowardsMouse);
Shoot();
}
}
public Vector2 GetDirectionTowardsMouse()
{
// convert player position to screen position (pixel coordinates)
Vector2 from = _mainCamera.WorldToScreenPoint(transform.position);
// mouse position is already in screen space
Vector2 to = Input.mousePosition;
// difference in positions, imagine this vector
// as an arrow starting at `from`, ending at `to`
Vector2 positionalDifference = to - from;
// normalizing the vector shortens it to 1 unit (represents only direction)
// ie. right=(1,0), down=(0,-1), diagonal up&right (0.707, 0.707)
return positionalDifference.normalized;
}
// calculates which sprite to select based on the given direction
public void UpdateSpriteDirection(Vector2 direction)
{
// divide a circle into slices for each sprite to represent
float sliceAngle = 360f / directionSprites.Length;
// calculate the direction's angle (-180 to 180 range)
float currentAngle = Mathf.Rad2Deg * Mathf.Atan2(direction.y, direction.x);
// offset the angle by half a slice to center the slices
// ie. when facing perfectly right, that's the center of a slice, not an edge
currentAngle += sliceAngle * 0.5f;
// put the angle range between 0 and 360 instead of -180 to 180
currentAngle = Mathf.Repeat(currentAngle, 360);
// get an index for which slice the direction is pointing
int sliceIndex = Mathf.FloorToInt(currentAngle / sliceAngle);
// set the sprite using that index (assuming sprites are in the array in counter clockwise order)
_spriteRenderer.sprite = directionSprites[sliceIndex];
}
void Shoot()
{
if (Input.GetButtonDown("Fire1"))
{
GameObject fired_bullet = Instantiate(BulletPrefab, FirePoint_2.position, FirePoint.rotation);
fired_bullet.GetComponent<Rigidbody2D>().velocity = FirePoint.up * 100f;
}
}
}