简体   繁体   English

如何在 unity2d 中将 Vector2 方向旋转 20 度?

[英]How can I rotate 20 degrees off of a Vector2 direction in unity2d?

I'm trying to cast a ray on Vector2.right and another ray on either side of it by 20 degrees.我正在尝试在 Vector2.right 上投射一条光线,并在其两侧投射另一条光线 20 度。

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.我想为transform.Rotate_direction(Vector2.right)位添加一个轻微的旋转。

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.提前致谢。

By multiplying the Quaternion behind the vector you can change its direction.通过将向量后面的Quaternion相乘,您可以改变其方向。 In your question, you need to use Quaternion.AngleAxis .在您的问题中,您需要使用Quaternion.AngleAxis

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM