Home > Back-end >  How can I rotate 20 degrees off of a Vector2 direction in unity2d?
How can I rotate 20 degrees off of a Vector2 direction in unity2d?

Time:08-05

I'm trying to cast a ray on Vector2.right and another ray on either side of it by 20 degrees.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PathFinding : MonoBehaviour
{
    public float speed = 5f;

    // Update is called once per frame
    private void Update()
    {
        //replace target.position with Camera.main.ScreenToWorldPoint(Input.mousePosition) to follow mouse pointer
        Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, speed * Time.deltaTime);

        if (Input.GetKey(KeyCode.Space))
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector2.right) * 10f, Color.green);
            RaycastHit2D front = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.right), 10f);
            if (front)
            {
                Debug.Log("Hit Something : "   front.collider.name);
                //hit.transform.GetComponent<SpriteRenderer>().color = Color.red;
                Debug.DrawRay(transform.position, transform.TransformDirection(Vector2.right) * 10f, Color.red);
            }
        
            RaycastHit2D left1 = Physics2D.Raycast(transform.position, transform.Rotate_Direction(Vector2.right), 10f);
        }
    }
}

It's just in the last line of code that I'm having a hard time. I want to add a slight rotation to the transform.Rotate_direction(Vector2.right) bit.

I'm pretty new to programming and especially to this here so if you could explain what you do and maybe show me how to implement it that would be greatly appreciated.

Thanks in advance.

CodePudding user response:

By multiplying the Quaternion behind the vector you can change its direction. In your question, you need to use Quaternion.AngleAxis.

Quaternion.AngleAxis(20f, Vector3.forward) * Vector2.right
  • Related