Rotating a polygon is not working in C# - c#

I'm trying to rotate a polygon in windows forms using C# and below is code written .
Please tell me what wrong in the code, there is no output on windows form.
Before and after rotation polygons not visible.
public void RotatePolygon(PaintEventArgs e)
{
pp[0] = new Point(624, 414);
pp[1] = new Point(614, 416);
pp[2] = new Point(626, 404);
e.Graphics.DrawPolygon(myPen2, pp);
System.Drawing.Drawing2D.Matrix myMatrix1 = new System.Drawing.Drawing2D.Matrix();
myMatrix.Rotate(45, MatrixOrder.Append);
myMatrix.TransformPoints(pp);
e.Graphics.Transform = myMatrix1;
e.Graphics.DrawPolygon(myPen, pp);
}
Thanks

You code does not compile if left unmodified. There are two matrices used - one declared in your method (myMatrix1) attached to the graphics object and one declared outside your method (myMatrix without the 1) used to explicitly transform the point array.
I tried the code with the required changes and it works flawless - I used myMatrix1 for both transformations and the effective rotation angle was, as expected, twice the one specified. So I guess you are using two transformation that cancel if the transformed points end where they began.

There could be this problems:
[1] your pens have no color/thickness (where do you define them?)
[2] your polygone is to big, so you only see the inside of it but not the border. --> Test Graphics.FillPolygon-Methode so you will see if [2] is right

You're both transforming the points and changing the transform matrix for the Graphics object - you need to do one or the other.
You also need to think about the fact that the rotate is going to be happing about (0,0) rather than about some part of the object - you may well need a translate in there too.
Bear in mind that TransformPoints just manipulates some numbers in an array - which you can easily inspect with the debugger - this will be a more effective technique than displaying an invisible object and wondering where it went.
Starting with a much smaller rotation angle (10 deg, perhaps?) may also help with the problem of losing the object - it will be easier to work out what's happening if you haven't moved so far.

Related

Check if object is within FOV (field of view) in Unity 3d

I am trying to create a game in Unity 3d where NPC's move and look around and check which objects are inside their view angle. To calculate what objects are inside the field of view angle i use unity's build in function Vector3.Angle, see:
// Get current position of the Robot.
var robotObjectPosition = currentTransform.parent.position;
// Get the direction to the object
var directionToObject = (objectToFind.transform.position - robotObjectPosition) / 2;
// Calculate the angle to the object and check if it's inside our viewAngle.
var isInsideAngle = Vector3.Angle(currentTransform.forward, directionToObject) < viewAngle / 2;
Now i have a weird problem where if i move to close to an object (a plane in the shape of a goal line in this case) the above check returns false, even though the object is still in front of it and the goal line is still clearly inside of his vision. I made a screenshot to visualize my problem.
In the first image the goal line is inside of his vision, but in the second ( i moved him a small step forward) the above function returns false, even though i can clearly see he is still in front of the object. I am geussing it has something to do with the width of the other object, (because i divide the viewangle by 2) but i havent been able to find a fix for it.
Mainly i would like to understand what is happening here.
I tried your code myself and got to the same result. The problem is you need to remember that the angle you are calculating has two important characteristics:
1. it checks for "objectToFind"'s center/pivot point. once the center is not inside the angle you will get false.
2. it is in 3D and not 2D so if you get closer the angle between the robot and the object (on the Y axis) does not include the center of the objectToFind.
As a solution I would cast a ray instead of checking if it is inside the angle range.
Hope that helps

Creating Custom Convex Hull & Mesh in Unity

I'm currently trying to implement a complex search field into a unity project I'm working on, where a user has the ability to spawn points into a scene. My goal is to create a custom shape for that user based on the points they created, and then I'd like to detect whether or not other objects are inside that shape, similar to the detection of a point inside a complex hull (still shaky on the theory behind that, but an example can be found here). If possible, I'd also like the shape to update itself if the points are later moved, giving it an almost elastic, stretchy feel.
So far, every tutorial or resource I've found online does the exact same basic example, where a script assigns new verts, UVs and triangles to a custom mesh to make a plane using two triangles, but this is frustratingly simple, and decidedly unhelpful when I simply don't know what the final shape will look like, or what triangles to actually draw even when the user has as little as five points in the scene.
As of right now, the closest visual representation I could come up with has a List keep track of the user's points, and a script that just draws a bunch of pseudo-triangles using LineRenderers to connect every point, even ones that aren't exterior faces, by iterating through the List multiple times. While this looks close to what I want, it isn't actually useful in any way, as I don't know how to 'fill' those faces, and I'm still relatively lost when it comes to whether or not an object is inside that hull, like the red sphere shown in the example below.
I can also destroy and redraw those lines repeatedly during the Update() method, which allows me to grab a point and move it around, resulting in the shape dynamically changing, but this results in an undesirable flashing effect that I'd sooner avoid for now.
As this is such a broad question, I've also included the method I'm using to draw these lines below, which parents a bunch of lines shaped like triangles to an empty game object for easy destruction and recreation:
void drawHull()
{
if (!GameObject.Find("hullHold"))
{
hullHold = new GameObject();
hullHold.name = "hullHold";
}
foreach(GameObject point in points)
{
for (int i = points.IndexOf(point); i < points.Count - 2; i++)
{
lineEdge = Instantiate(lineReference);
lineEdge.name = "Triangle" + i;
lineEdge.GetComponent<LineRenderer>().startColor = Color.black;
lineEdge.GetComponent<LineRenderer>().endColor = Color.black;
lineEdge.GetComponent<LineRenderer>().positionCount = 3;
lineEdge.GetComponent<LineRenderer>().SetPosition(0, points[points.IndexOf(point)].transform.position);
lineEdge.GetComponent<LineRenderer>().SetPosition(1, points[i + 1].transform.position);
lineEdge.GetComponent<LineRenderer>().SetPosition(2, points[i + 2].transform.position);
lineEdge.GetComponent<LineRenderer>().loop = true;
lineEdge.SetActive(true);
lineEdge.transform.SetParent(hullHold.transform);
}
}
}
If anyone has encountered a similar problem somewhere else that I simply couldn't find, please let me know! Anything from more knowledge on creating a custom mesh to a more in depth and beginner-friendly explanation on determining if a point is inside a convex hull would be quite helpful. If it's at all relevant, I am working in VR and running version 2018.2.6f1 to ensure that the Oculus rift package and Unity play nice, but I haven't been having any issues working in an environment a few months behind.
Thanks!
You do mention assinging verts and tris to a mesh - this is the 'right' way to do it in unity, as it ties in with highly optimized MeshRenderer, and also I believe Colliders are able to use meshes where given the shapes like that, so you should be able to just plug into PhysX and query it for colliders overlaping with your mesh. Doing it by hand, aka iterating through faces and establishing actual bounds of your object is actually pretty hard to do effectively

How to randomly place objects as player move around in an infinity map without overlap?

I trying to make a game where player only move forward in an infinity map, and the path (just thing of them like points, the path is only the visual) is procedurally generated. I want those path to have different length (something like the tree of life, but only branches of the selected path are generated).
This is how I generate branches without overlap:
List<Vector3> everyPos; //predetermined position
public void Spawn(int amount)
{
List<Vector3> possiblePos = new List<Vector3>(everyPos);
for (int i = 0; i < amount; i++)
{
int index = Random(0, possiblePos.Count); //Find a random position
SpawnObjectAt(currentPosition+possiblePos[index]));//Create a point there
possiblePos.RemoveAt(index); //Remove that position from the list
}
}
The problem is , look at this image(I can't embed image yet):
Red is where player start, green is possible spawn position in the first move.
If there are 2 point spawned at 1 and 2, player choose point1, then the possible position in the second time will be a point in the black zone, which include point2, so if I keep continue there will eventually overlap.
How can I avoid this? I'm making a mobile game so I don't want to cache every single point. Any help would be really appreciated! Thanks!
This is a small web game that have somewhat similar mechanic to what I trying to achieve: newgrounds.com/portal/view/592325/
This is an attempt here to answer, but honestly, you need to provide more information.
Depending on the language you are writing in, you can handle this differently. You may need dynamic allocation, but for now lets assume, since your idea is quite small, that you can just do one large array predefined before compile time.
I assume you know how to make an array, so create one with say, 500 length to start. If you want to 'generate' a link like they did in that game, you simply need a random function, (there is a built in library in pretty much every language I think) and you need to do a little math.
Whatever language you use will surely have a built in graphics library, or you can use a popular easy to use one. I'll just draw a picture to make this clear.
There are a number of ways you can do this mathematically as shown in the image, using angles for example, the simplest way, however, is just to follow the boxes.
If you have worked with graphics before, you know what a vector is, if not, you will need to learn. The 9 vectors presented in this image (0,1) (1,0) (1,1) etc. can be created as vector objects, or even stored as individual ints.
To make your nodes 'move' into another path, you can simply do a rand 1-9 and then correlated the result to one of 9 possible vectors, and then add them to your position vector. It is easiest to do this in array and just use the rand int as the index. In most c derived languages you do that like this:
positionVector += changeVectorArray[rand(1,9)];
You then increment your position vector by one of the 9 vectors as shown above.
The simplest way of making the 'path' is to copy the position before you add the change vector, and then store all of the changes sequentially in another 'path' array.
To show the path on screen, simply draw a line between the first and second, second and third, third and forth elements of your path array. This formula (of joining lines) is discrete mathematics if I'm not mistaken, and you can do much more complicated path shapes if you want, but you get the gist.
That should at least start you off. Without more info I can't really help you.
I could go off on a tangent describe a bunch of different ways you can make this happen differently but its probably easier if you just ask for specifics.
EDIT>>>
Continuing with this answer, yes, looking at it now, the nodes can definitely overlap. To solve this problem you could use collision detection, every time you generate a new 'position', before adding it and drawing the line you have to loop through your array like this:
boolean copy = true;
for(int i = 0; i < getLength(pathArray); i++){
if( newVector == pathArray[i]){
copy=false;
}
}
Then of course, if copy still is true, copy the new position int the pathArray. NOTE: this whole solution is sloppy as hell, and as your array gets larger, your program is going to take longer and longer to search through that loop. This may not also guarantee that the path goes in one direction, but it is likely. And note that the lines will still be able to overlap each other, even though the position vectors can't be on top of one another.
All this considered, I think it will work, the optimization is up to you. I would suggest that there is probably a much more efficient solution using a discrete formula. You can also use such a formula to make the path go in particular directions and do other more complicated things.
You could also quite easily apply constraints on your random rolls if you want to make the path go in a particular direction. But there are so many ways of doing this I can't begin to explain. You could google path-finding algorithms for that.
Good luck.

C# (OpenTK) incorrect rendering

I'm going through OpenGL 3.3+ tutorial written in C++ and I'm converting my code to C# (using OpenTK). In the tutorial there's a VectorBufferObject using vector<BYTE> to hold data for buffer. Unfortunately I did not manage to achieve same functionality using List<byte>, because I was unable to convert Vector3 to byteArray the way it could be used by DrawArrays function.
But well, I've decided to store List<float> instead and following the tutorial I store all floats (3 for position + 2 for texture coords for each vertice) in a single List of VectorBufferObject.
Apart from not rendering textures properly (my mistake I believe, not important at the moment really) it should work just fine, BUT - it should render a cube and a pyramid rotating - it does render a triangle and a rectangle. I've checked it with PolygonMode.Line and I can tell that the rectangle is made of more than 2 triangles (it has box-type lines going across, not a single one that should be there when drawn with 2 triangles)). I therefore suspect they are drawn one over another. I can't figure out why really.
Below is source code of relevant classes. Please ask if there is a need for more information.
#EDIT
Despite my huge hope of following the tutorial, I'd consider an alternative, not overly complicated alternative to that solution.
RenderingEngine.cs
http://pastebin.com/gtnX4ESg
VectorBufferObject.cs
http://pastebin.com/veGwybp7
Static_Geometry.cs
http://pastebin.com/K1bJ8z8u

How To Make a Tetris Clone?

I am working on coding a Tetris clone in XNA C# and am unsure of the best way to approach the data structure side of the game on a high level.
I am totally fine with the collision detection, rotations, animation etc. What I need to know the best way to do the storing of "dropped blocks" - ie blocks that are no longer under tha player's control.
I think that each Tetromino block should be stored in its own class that consists of a 4x4 array so that the block can easily be rotated. The problem is then how to I store the tetromino's final position into the game grid by then cutting the tetromino up into individual blocks(for each cell) and then set the main game grid's corresponding positions to hold these same blocks, then disappearing the tetromino once it has reached its final position. Maybe there is some drawback to my method.
Should I create a 10x20 matrix for the main game grid which can then store? or should I use stacks or queues to somehow store the dropped blocks. Or maybe there is some better method/data structure to store things?
I am sure my way would work, but I am reaching out to see if anybody knows a better way or if my way is good enough?
P.S. Not homework, this will be a project for my portfolio. Thanks.
Once a block is immobile, there's nothing that distinguishes it from any other block that is now immobile. In that regard, I think it makes the most sense to store the entire grid as a matrix, where each square is either filled or not (along with the color of the block if it is).
I feel like the matrix has many advantages. It'll make collision detection simple (no having to compare with multiple objects, just locations on a matrix). Storing it as a matrix will also make it easier to determine when a full line has been created. On top of that, you don't have to worry about splicing an immobile Tetromino when a line disappears. And when one does, you can just shift the entire matrix down in one fell swoop.
This smells like homework, but my take on an object-oriented approach to Tetris would be to have each individual square be an object, and both "blocks" (tetrominos) and the grid itself would be collections of the same square objects.
Block objects manage the rotation and position of the falling squares, and the grid handles displaying them and detroying completed rows. Each block would have a colour or texture associated with it that would be provided by the original block object it came from, but otherwise squares at the base of the grid would have no other indication that they were ever part of the same original block.
To elaborate, when you create a new block object, it creates a set of 4 squares with the same colour/texture on the grid. The grid manages their display. So when the block hits the bottom, you just forget about the block, and the squares remain referenced by the grid.
Rotations and dropping are operations only a block need deal with, and only one its four squares (though it will need to be able to query the grid to make sure the rotation can fit).
Not making blocks actually look like autonomous blocks is - in my opinion - a big failing of many a Tetris clone. I put special effort into ensuring my clone always looked right, whether the block is still "in play" or dropped. This meant going slightly beyond the simple matrix data structure and coming up with something that supported the concept of "connection" between block parts.
I had a class called BlockGrid that is used as a base class for both a Block and the Board. BlockGrid has an abstract (pure virtual in C++) method called AreBlockPartsSameBlock that subclasses must override to determine whether two different block parts belong to the same block. For the implementation in Block, it simply returns true if there are block parts at both locations. For the implementation in Board, it returns true if both locations contain the same Block.
The BlockGrid class uses this information to "fill in" the details in the rendered blocks, so that they actually look like blocks.
Using arrays would be the easiest way to handle tetris. There is a direct correlation between what you see on screen and the structures used in memory. Using stack/queues would be an overkill and unnecessarily complicated.
You can have 2 copies of a falling block. One will be for display (Alpha) and the other one will be movement (Beta).
You will need a structure like
class FallingBlock
{
int pos_grid_x;
int pos_grid_y;
int blocks_alpha[4][4];
int blocks_beta[4][4];
function movedDown();
function rotate(int direction();
function checkCollision();
function revertToAlpha();
function copyToBeta()
};
The _beta array would be move or rotated and checked against the board for collisions. If there is a collision, revert it to _alpha, if not, copy _beta onto _alpha.
And if there is a collision on movedDown(), the block's life is over and the _alpha grid would have to copied onto the game board and the FallingBlock object deleted.
The board would of course have to be another structure like:
class Board
{
int gameBoard[10][20];
//some functions go here
}
I used int to represent a block, each value (like 1,2,3) representing a different texture or color (0 would mean an empty spot).
Once the block is part of the gameboard, it would only need a texture/color identifier to be displayed.
I actually just did this a few days ago except in WPF rather than XNA. Here's what I did:
Edit:
Seems like I define "Block" differently than other people. What I define as a Block is one of 4 cells that make up a Tetromino, and an actual Tetromino itself as a Piece.
Have a Block as a struct that had X, Y coordinates and Color. (I later added a bool IsSet to indicate whether it was in a floating piece or on the actual board, but that was just because I wanted to distinguish them visually)
As methods on Block, I had Left, Right, Down, and Rotate(Block center) which returned a new shifted Block. This allowed me to rotate or move any piece without knowing the shape or orientation of the piece.
I had a generic Piece object that had a List of all the blocks it contained and the index of the Block that was the center, which is used as the center of rotation.
I then made a PieceFactory that could produce all the different pieces, and with a Piece not needing to know what kind of piece it was, I could (and did) easily add variation of Pieces consisting of more or less than 4 Blocks without needing to create any new classes
The Board consisted of a Dictionary which was all the blocks that were currently on the board, as well as the dimensions of the board that was configurable. You can use a Matrix just as well probably, but with a Dictionary I only needed to iterate through Blocks without white spaces.
My Solution (design), with examples in Python as a good substitute for pseudo code.
Use a grid 20 x 10, that the tetrominoes fall down.
Tetrominoes are made up of blocks, which have attributes of coordinate (x,y) and colour.
So, for example, the T-shape tetrominoe looks like this...
. 4 5 6 7 8 .
.
19 # # #
20 #
.
Thus, the T-shape is a collection of blocks with the coords (5,19), (6,19), (7,19), (6,20).
Moving the shape is a matter of applying a simple transformation to all the coords in the group. e.g. to move the shape down add (0,1), left (-1,0) or right (1,0) to all coords in the collection that make the shape.
This also lets you use some simple trig to rotate the shape by 90-degrees. The rule is that when rotating 90-degrees relative to an origin, then (x,y) becomes equal to (-y,x).
Here is an example to explain it. Taking the T-shape from above, use the (6,19) as the centre block to rotate around. For simplicity, make this the first coordinate in the collection, so...
t_shape = [ [6,19], [5,19], [7,19], [6,20] ]
Then, here is a simple function to rotate that collection of coordinates by 90-degrees
def rotate( shape ):
X=0 # for selecting the X and Y coords
Y=1
# get the middle block
middle = shape[0]
# work out the coordinates of the other blocks relative to the
# middle block
rel = []
for coords in shape:
rel.append( [ coords[X]-middle[X], coords[Y]-middle[Y] ] )
# now rotate 90-degrees; x,y = -y, x
new_shape = []
for coords in rel:
new_shape.append( [ middle[X]-coords[Y], middle[Y]+coords[X] ] )
return new_shape
Now, if you apply this function to our collection of coordinate for the T-shape...
new_t_shape = rotate( t_shape )
new_t_shape
[[6, 19], [6, 18], [6, 20], [5, 19]]
Plot this out in the coordinate system and it looks like this...
. 4 5 6 7 8 .
.
18 #
19 # #
20 #
.
That was the hardest bit for me, hope this helps someone.
Keep in mind that a previous winner of the Obfuscated C Code Contest implemented a pretty good tetris game (for VT100 terminals on BSD unix) in fewer than 512 bytes of obfuscated C:
long h[4];t(){h[3]-=h[3]/3000;setitimer(0,h,0);}c,d,l,v[]={(int)t,0,2},w,s,I,K
=0,i=276,j,k,q[276],Q[276],*n=q,*m,x=17,f[]={7,-13,-12,1,8,-11,-12,-1,9,-1,1,
12,3,-13,-12,-1,12,-1,11,1,15,-1,13,1,18,-1,1,2,0,-12,-1,11,1,-12,1,13,10,-12,
1,12,11,-12,-1,1,2,-12,-1,12,13,-12,12,13,14,-11,-1,1,4,-13,-12,12,16,-11,-12,
12,17,-13,1,-1,5,-12,12,11,6,-12,12,24};u(){for(i=11;++i<264;)if((k=q[i])-Q[i]
){Q[i]=k;if(i-++I||i%12<1)printf("\033[%d;%dH",(I=i)/12,i%12*2+28);printf(
"\033[%dm "+(K-k?0:5),k);K=k;}Q[263]=c=getchar();}G(b){for(i=4;i--;)if(q[i?b+
n[i]:b])return 0;return 1;}g(b){for(i=4;i--;q[i?x+n[i]:x]=b);}main(C,V,a)char*
*V,*a;{h[3]=1000000/(l=C>1?atoi(V[1]):2);for(a=C>2?V[2]:"jkl pq";i;i--)*n++=i<
25||i%12<2?7:0;srand(getpid());system("stty cbreak -echo stop u");sigvec(14,v,
0);t();puts("\033[H\033[J");for(n=f+rand()%7*4;;g(7),u(),g(0)){if(c<0){if(G(x+
12))x+=12;else{g(7);++w;for(j=0;j<252;j=12*(j/12+1))for(;q[++j];)if(j%12==10){
for(;j%12;q[j--]=0);u();for(;--j;q[j+12]=q[j]);u();}n=f+rand()%7*4;G(x=17)||(c
=a[5]);}}if(c==*a)G(--x)||++x;if(c==a[1])n=f+4**(m=n),G(x)||(n=m);if(c==a[2])G
(++x)||--x;if(c==a[3])for(;G(x+12);++w)x+=12;if(c==a[4]||c==a[5]){s=sigblock(
8192);printf("\033[H\033[J\033[0m%d\n",w);if(c==a[5])break;for(j=264;j--;Q[j]=
0);while(getchar()-a[4]);puts("\033[H\033[J\033[7m");sigsetmask(s);}}d=popen(
"stty -cbreak echo stop \023;cat - HI|sort -rn|head -20>/tmp/$$;mv /tmp/$$ HI\
;cat HI","w");fprintf(d,"%4d on level %1d by %s\n",w,l,getlogin());pclose(d);}
http://www.ioccc.org/1989/tromp.hint
I'm by no means a Tetris expert, but as you described a 10x20 matrix seems like a natural choice to me.
It will make it very easy when the time comes to check if you have completed a line or not, and dealing with it. Simply iterating over the 2d-array looking at boolean values of each position to see if they add up to 10 block positions.
However, you'll have some manual clean up to do if there is a completed line. Having to shift everything down. All though it isn't that big of a deal when it comes down to it.
Using Simon Peverett logic, here is what I ended up with in c#
public class Tetromino
{
// Block is composed of a Point called Position and the color
public Block[] Blocks { get; protected internal set; }
// Constructors, etc.
// Rotate the tetromino by 90 degrees, clock-wise
public void Rotate()
{
Point middle = Blocks[0].Position;
List<Point> rel = new List<Point>();
foreach (Block b in Blocks)
rel.Add(new Point(b.Position.x - middle.x, b.Position.y - middle.y));
List<Block> shape = new List<Block>();
foreach (Point p in rel)
shape.Add(new Block(middle.x - p.y, middle.y + p.x));
Blocks = shape.ToArray();
}
public void Translate(Point p)
{
// Block Translation: Position+= p;
foreach (Block b in Blocks)
b.Translate(p);
}
}
Note: Using XNA, Point structure could be swapped for Vector2D
in my example (Java) - all figures have lists of blocks - which can be removed whenever needed. Also in my Board class I have a list of figures and a field variable figure - which is controlled by the user. When the figure is "landed" - it goes into the list of other figures, and a new figure is made controllable by the user.
A better explanation here: http://bordiani.wordpress.com/2014/10/20/tetris-in-java-part-i-overview/

Categories

Resources