簡體   English   中英

如何在 unity2d 中將 Vector2 方向旋轉 20 度?

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

我正在嘗試在 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);
        }
    }
}

只是在最后一行代碼中我遇到了困難。 我想為transform.Rotate_direction(Vector2.right)位添加一個輕微的旋轉。

我對編程很陌生,尤其是這里的這個,所以如果你能解釋你所做的事情,並可能告訴我如何實現它,我將不勝感激。

提前致謝。

通過將向量后面的Quaternion相乘,您可以改變其方向。 在您的問題中,您需要使用Quaternion.AngleAxis

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM