Y
Y
Yura Berezovsky2017-03-30 16:58:54
C++ / C#
Yura Berezovsky, 2017-03-30 16:58:54

How to find out the angle between the object's direction of flight and the x-axis?

I wanted to add a script so that it wraps the bullet prefab by 180 if it was fired to the left.

using UnityEngine;
using System.Collections;

public class Shooting2 : MonoBehaviour
{
    public GameObject rocket;
    public float speed;
    public KeyCode Fire = KeyCode.F;
    public SwordScript shooted;
    private Animator anims;
    private float vertical;
    private float horizontal;
    private Rigidbody2D body;
    public float angle;
    void FixedUpdate()
    {
        if (Input.GetKeyDown(Fire))
        {
            Vector3 worldMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Vector2 direction = (Vector2)((worldMousePos - transform.position));
            direction.Normalize();
            GameObject bullet = (GameObject)Instantiate(
                                    rocket,
                                    transform.position + (Vector3)(direction * 0.5f),
                                    Quaternion.identity);
            bullet.GetComponent<Rigidbody2D>().velocity = direction * speed;
            bullet.AddComponent<Animator>();
            bullet.AddComponent<SwordScript>();
            //Участок снизу должен узнать угол между направлением пули и осью х и перевернуть префаб.
            Vector2 targetDir = bullet.GetComponent<Transform>().position - transform.position;
            float angle = Vector2.Angle(targetDir, transform.right);           
            if (angle > 90f && angle < 180f)
            {
                shooted.Flip();
            }
        }
    }
    void Start()
    {
        anims = GetComponent<Animator>();
        anims.SetFloat("flying", 2);

        body = GetComponent<Rigidbody2D>();
        shooted = GetComponent<SwordScript>();
    }
}

I just don't understand why it doesn't work properly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shagguboy, 2017-03-30
@shagguboy

The cosine of the angle between vectors is equal to the scalar product of the vectors divided by the product of the absolute values ​​of the vectors.

geometry, grade 9.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question