Question by
unity_qsHT3W_Izmg_PQ · Jan 31 at 10:26 AM ·
2d game2d sprites2d animation2d rotation
How to rotate sword while still looking at mouse?
I want to rotate the sword while sword is still pointing at mouse. I don't know what to use, since animations don't really work for me, and so does transform.Rotate()
. This is my script:
[SerializeField] Camera cam;
Vector2 swordPos;
Vector2 mousePos;
void FixedUpdate()
{
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
swordPos = new Vector2 (transform.position.x, transform.position.y);
Vector2 lookDir = mousePos - swordPos;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
transform.rotation = Quaternion.Euler(0, 0, angle);
}
I also want to use: if( Input.GetButton("Fire1") )
Comment
Answer by andrew-lukasik · Jan 31 at 12:03 PM
using UnityEngine;
public class SwordAnimator : MonoBehaviour
{
[SerializeField] Camera _camera = null;
[SerializeField] Transform _sword = null;
[SerializeField] Vector3 _rotationPerSecond = new Vector3( 0 , 200 , 0 );
Vector3 _dir;
void Start ()
{
_dir = _sword.up;// initial dir
}
void Update ()
{
if( Input.GetButton("Fire1") )
{
_dir = _camera.ScreenToWorldPoint( Input.mousePosition ) - _sword.position;
}
float lookAtAngle = Mathf.Atan2( _dir.y , _dir.x ) * Mathf.Rad2Deg -90f;
_sword.rotation = Quaternion.Euler(0,0,lookAtAngle) * Quaternion.Euler(_rotationPerSecond*Time.time);
}
}
Your answer
Follow this Question
Related Questions
Factorio-like sprite directions 0 Answers
How Do I Add Sprites To 2D Skinning Editor ? 0 Answers
I can't seem to rotate my character depending on what side he is running to (2D sidescroller) 0 Answers
how can i anchor a point of a sprite to make it swing? 1 Answer
2D Animation Feet Pivot Point 0 Answers