# Ideas on getting part of a 2d array

## Recommended Posts

So to render my game I have a imaginary triangle that gets all the objects in a 2d array in front of the player.

So I can get all the objects that intersect the red triangle.

But how do I get the ones inside the triangle?

##### Share on other sites

Sounds like an interesting problem but I'm a little unclear about what you are asking.

Are you already able to get the objects you have highlighted in blue in your diagram? Are you trying to get the objects that are fully inside the triangle and that, therefore, don't bisect the lines that form the triangle?

##### Share on other sites

If you already have all your blue grid cells in a list, you could use something like the methods used in this raycasting demo to work out which ones the red lines go through.

http://gamemechanicexplorer.com/#raycasting-1

Eliminate those cells from your list and you are left with just the ones that are 'inside' the triangle.

##### Share on other sites

Sounds like an interesting problem but I'm a little unclear about what you are asking.

Are you already able to get the objects you have highlighted in blue in your diagram? Are you trying to get the objects that are fully inside the triangle and that, therefore, don't bisect the lines that form the triangle?

Well, I have the blue ones that intersect the line but not the blue ones that don't. I'm trying to get the blue ones I don't have

##### Share on other sites

I would filter the array using a point-triangle collision detection, e.g. http://codepen.io/anon/pen/EVJKNQ

`    inTriangle = _.filter(mappedArr, function(cell) {      return pointInTriangle(triangle, cell);    });`

For this example, I've flattened the 2D array into a 1D array with x and y values stored in the array, as that means I can use a filter function more easily.

For point-triangle detection, I've used this simple check:

`function side(t0, t1, pt) {    return (t1.y - t0.y) * (pt.x - t0.x) + (-t1.x + t0.x) * (pt.y - t0.y);  }function pointInTriangle(t, pt) {  var checkSide1 = side(t[0], t[1], pt) >= 0;  var checkSide2 = side(t[1], t[2], pt) >= 0;  var checkSide3 = side(t[2], t[0], pt) >= 0;  return checkSide1 && checkSide2 && checkSide3;}`

Also, I've used lodash in the example - I use it quite a lot and I like the syntax - but there is nothing I've used it for you couldn't do easily without.

##### Share on other sites

All modern browsers support Array.filter, I'm not sure theres a requirement for lodash here. Similarly they all also support Array.map. I'm also not a fan of using `triangle` from outside of the critical function, but thats probably just for convenience for the demo.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.