繁体   English   中英

如何在多边形上获得Y位置

[英]How get an Y position on a Polygon

我在Java 2D游戏中有一个多边形。 如何从多边形上的给定X位置获取多边形上的Y位置。

看图片:

游戏,多边形

我想将玩家放在十字架上,但是我不知道如何找出多边形上的Y位置。

这是更多信息,多边形的类型为http://docs.oracle.com/javase/7/docs/api/java/awt/Polygon.html

它是如何创建的:

 private void paintGround(Graphics2D g2d){
    int width =  gameBoard.getWidth(); //1000
    int height = gameBoard.getHeight(); //750
    int xCoords[] = {0,0,width/2,width,width};
    int yCoords[] = {height,height/2,height/2-100,height/2,height};
    g2d.setColor(Color.white);
    Polygon polygon = new Polygon(xCoords, yCoords,5);
    g2d.fillPolygon(polygon);
    }

谢谢您的时间,对不起这个愚蠢的问题:)

如果有人感兴趣的话,这里是git: https : //github.com/davli921/Smrow.git

这是获取两个顶点之间特定点的高度的更通用的解决方案:

  • 将“山”定义为一个数组,其中的索引表示X值,实际内容表示Y (高度)值。
  • 使用此信息可基于“玩家”的当前X值计算其Y位置。
  • 绘制结果。

下面的示例已使用Javascript实现,因此任何人都可以在其浏览器中轻松尝试它,但是原理是相同的,无论您使用哪种语言。 首先,我们需要定义一些基本的HTML,以便绘制一个画布:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Example</title>
  </head>
  <body>
    <canvas id="game_canvas" width="400" height="300">You must enable Javascript</canvas>
    <script src="game.js"></script>
  </body>
</html>

现在,这是重要的部分-Javascript:

"use strict";

// This series of points represents the "height" values of the landscape.
var points = [10, 50, 150, 20, 100, 10];

// Let's pick a random X position...
var x = Math.random() * (points.length-1);

// We can get the height at a given point by interpolating the vertices:
var v1 = points[Math.floor(x)];
var v2 = points[Math.ceil(x)];
var y = v1 + ((v2-v1) * (x % 1.0));

// Now let's draw the "game" state...
var canvas = document.getElementById("game_canvas");
var ctx = canvas.getContext("2d");
var x_scale = canvas.width / points.length;

// This is the "world"...
ctx.moveTo(0, points[0]);
for (var p = 1; p < points.length; ++p) { ctx.lineTo(x_scale * p, points[p]); }
ctx.stroke();

// ...and this is the "player".
ctx.fillStyle = "red";  
ctx.fillRect((x * x_scale)-4, y-4, 8, 8);

将这些文件保存到本地文件夹(确保JS文件另存为game.js ),然后在浏览器中打开HTML文件:

图片

F5刷新页面(从而选择一个新的随机X位置)。

暂无
暂无

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

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