c# - 从圆的中心点计算 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));
解决方案
在您的 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;
推荐阅读
- php - 嵌套 Livewire 组件在更新时重置值
- audio - 使用 arnndn 过滤器时未找到 FFmpeg 选项“混合”
- java - 信息安全项目。提取指定文件的签名
- apache-kafka - ConsumerAwareRebalanceListener 实现
- javascript - 基于另一个数组对数组中的值求和
- javascript - 将对象数组过滤成两个新数组并将每个数组保存到 useState
- jenkins - 将 terraform local-exec 配置器与 jenkins 集成
- lisp - 如何停止从 LISP 中的 if 语句中获取 NIL
- firebase - 如何在firebase中创建具有文档编号的新文档,但我需要在单个请求中进行
- javascript - 当设置为 ie >= 11 时,带有 @rollup/plugin-babel 的 vite/rollup 不会去除模板文字反引号