首页 > 解决方案 > 从圆的中心点计算 x 和 y 位置

问题描述

我知道以前有人问过这个问题,并且我检查了很多帖子,我意识到我的数学不足以解决这个问题。

我有一个圆,它是 x = 0.0 & y = 0.0 处的中心点。基于度数,在本例中为 270,我想将 x-box 放置在距离中心点指定度数的 x 和 y 上。我就是做错了,即使是我找到的例子。下面是我测试的当前代码以及 270 度测试的结果,x-box 定位错误,因为它不是 270 度角。

我将不胜感激任何帮助。

在此处输入图像描述

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

public class testscript : MonoBehaviour
{

    public Image im1, im2;
    public Text im1txt, im2txt, deg;
    private float degree = 270f; 
    private float x, y;


    void Start()
    {
        im1.rectTransform.anchoredPosition = new Vector2(0f, 0f);
        im1txt.text = im1.rectTransform.anchoredPosition.ToString();


        deg.text = degree + " degrees";

        x = 0f + (100 * Mathf.Cos(degree * Mathf.PI / 360f));
        y = 0f + (100 * Mathf.Sin(degree * Mathf.PI / 360f));


        im2.rectTransform.anchoredPosition = new Vector2(x, y);
        im2txt.text = im2.rectTransform.anchoredPosition.ToString();


    }


}

I have tested the two suggestions below and basically get the same result as all the others. Let me visualize the result I get with the last test I done:

const float deg_to_rad = 2f * Mathf.PI / 360f;
    var radians = degree * deg_to_rad;
    x = 0 + Mathf.Cos(radians) * 100;
    y = 0 + Mathf.Sin(radians) * 100;

Here is the result:

[![enter image description here][2]][2]

Solution is, Sin and Cos was swapped. Thanks J.Lengel:

float x = 1f + (100 * Mathf.Sin(angelDegree * Mathf.PI / 180));
float y = -14f + (100 * Mathf.Cos(angelDegree * Mathf.PI / 180));

标签: c#unity3d

解决方案


在您的 Math.cos 和 Math.sin 中,您通过除以 360 将度数转换为弧度。这不起作用,因为 360 度相当于 2pi 的弧度而不是 pi。这意味着您必须除以 180,或将度数乘以 2。希望对您有所帮助!

我注意到你为 x 取余弦,为 y 取 sin。交换这个;你想顺时针走,你这样做的方式是逆时针走。

x = x_origin + Math.sin(angle) * radius;
y = y_origin + Math.cos(angle) * radius;

推荐阅读