【问题标题】:Rotating an equilateral triangle at its center在中心旋转等边三角形
【发布时间】:2020-03-31 23:15:35
【问题描述】:

我正在编写 Java Graphics 类的 Kotlin 函数,它将填充一个中心在给定坐标处的等边三角形。我现在正在尝试添加旋转三角形的功能,以度为单位给出theta

读入点旋转,我发现方程x′ = xcosθ − ysinθy′ = ycosθ + xsinθ 除了将xy 转换为旋转前的原点,然后将结果转换回来,似乎是我的解决方案正在寻找。

但是,在实施时,三角形似乎几乎在模拟 3D 空间中旋转。

我的代码

fun Graphics.fillTriangle(x: Int, y: Int, sideLength: Int, theta: Int = 0) {
    var xCords = arrayOf(x - (sideLength / 2),
                         x + (sideLength / 2),
                         x)

    var yCords = arrayOf((y + (sideLength / (2 * sqrt(3.0)))).toInt(),
                         (y + (sideLength / (2 * sqrt(3.0)))).toInt(),
                         (y - (sideLength / sqrt(3.0))).toInt())

    if(theta != 0) {
        for(i in 0..2) {
            xCords[i] = ((xCords[i]-x) * cos(toRadians(theta)) - (yCords[i]-y) * sin(toRadians(theta))).toInt() + x
            yCords[i] = ((yCords[i]-y) * cos(toRadians(theta)) + (xCords[i]-x) * sin(toRadians(theta))).toInt() + y
        }
    }

    fillPolygon(xCords.toIntArray(), yCords.toIntArray(), 3)
}

我的实现有什么问题吗?

【问题讨论】:

    标签: kotlin graphics rotation


    【解决方案1】:

    我没有检查你的数学,但我会建议一种更简单的方法。对于每个点,计算以原点为中心的三角形的位置,然后添加偏移量。等边三角形只是一个圆上的三个点,相距 120 度,所以数学就是 (x, y) = (r*cos(theta), r*sin(theta))

    fun Graphics.fillTriangle(x: Int, y: Int, sideLength: Int, theta: Int = 0) {
        val radius = sideLength / sqrt(3.0)
        val angles = (0..2).map { it * (toRadians(theta) + toRadians(120)) }
        val xCoords = angles.map { (radius * cos(it) + x).roundToInt() }.toIntArray()
        val yCoords = angles.map { (radius * sin(it) + y).roundToInt() }.toIntArray()
        fillPolygon(xCoords, yCoords, 3)
    }
    

    【讨论】:

    • 我用我的方法弄明白了,但感谢您的简化;这更直观。
    【解决方案2】:

    我想通了。我正在修改xCord 数组中的坐标,然后用它来计算yCord 数组中的新坐标。

    我的新代码

    var newX = (((xCords[i]-x) * cos(toRadians(theta)) - (yCords[i]-y)*sin(toRadians(theta)))+ x).toInt()
    var newY = (((yCords[i]-y) * cos(toRadians(theta)) + (xCords[i]-x) * sin(toRadians(theta))) + y).toInt()
    
    xCords[i] = newX
    yCords[i] = newY
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-24
      • 2016-07-30
      • 2016-03-19
      • 2013-02-07
      • 1970-01-01
      • 1970-01-01
      • 2023-01-08
      • 2016-06-10
      相关资源
      最近更新 更多