How to make a sprite point at the mouse. XNA C# - sprite

If you would look at this diagram link text, I need to find angle A by only knowing the length of all sides of a right triangle.
I don't know trig and need some help.

There are actually 2 questions in your post.
How to make a sprite point at the mouse. XNA C#:
You will have to calculate the direction between the position of the sprite and the position of the mouse.
This can be done using trigonometry functions. In this case: Arctangens2
So let's use the math library:
MouseState mouseState = Mouse.GetState();
Math.Atan2((double)mouseState.Y - sprite.Y, (double)mouseState.X - sprite.X); //this will return the angle(in radians) from sprite to mouse.
In your trigonometry example you will see that those values actually are:
Math.Atan2(BC, AC);
or
Math.Atan2(Ydiff, Xdiff);
I hope this helps =D
Cheers,
TomHashNL

I found my final solution to be:
Vector2 direction = targetPosition - currentPosition;
direction.Normalize();
float rotationInRadians = (float)Math.Atan2((double)direction.Y,
(double)direction.X) + MathHelper.PiOver2;
rotationInRadians is a raw value that can be passed to the sprite batch for the correct rotation amount--no further code is needed. Also, you may notice incorrect results if you're rotating the sprite on a corner rather than the middle.

Related

Collision detection & resolution: circle in a playfield of other circles and polygons

I am working on a game that has a player sprite surrounded by a collision circle of a known radius. The player sprite can move about a playfield that consists of other sprites with their own collision circles and other obstacles made up of polygons. The other obstacles are rectangles at a 45 degree angle.
In addition, I want the player to adjust its movement when it does collide. I want the player to try to "push through" past the object instead of being stopped by it.
For example, if the player were to collide with another sprite's bounding circle, it would be stopped if its vector was exactly perpendicular to the tangent of the two circles' intersection.
However, if not perfectly perpendicular, the player would be, slowly at first, then faster, pushed along the tangent of the circle until it can continue past it unimpeded.
This works similarly when encountering one of the 45 degree rectangles.
What I need help with is the following: I am trying to find an analytic solution to detect both other sprites and obsticles, have the player's movement adjusted, and possibly stopped when adjusted to wedge between two or more objects.
I can do the collision detection and deflection for one object type at a time, but am struggling to put everything together into a comprehensive algorithm. I am currently working on an iterative pairwise resolution approach that "tries" different locations to result in a best-guess solution, but I really want a mathematically analytic solution. I'm hoping to have a function something like what appears in this psuedocode.
x = [player's x location]
y = [player's y location]
r = [player's collision radius]
// Array of other sprites on the playfield,
spr = [other sprites array]
// which contains 3 parameters, x, y, r. E.g., spr[3].x or spr[3].r,
// for the x position or collision radius for the fourth sprite in the
// array.
// Array of 45 degree rectangles on the playfield,
rect = [array of rectangles]
// which contain 4 parameters, x1, y1, x2, y2, the two opposite points
// of the rectangle. E.g., rect[0].x1, for the x position of the first
// point of the first rectangle.
// For simplicity, assume the above variables are all directly accessable
// in the function below.
// requestX and requestY is the position to which the player would
// like to move the player sprite.
definefunction collisionAdjustor(requestX, requestY) {
// Here I'd like to adjust the requested position if needed because
// of an intersection with one or more other sprites or rectangles.
// Finally return the location at which the player will actually be
// arriving.
return destinationX, destinationY
}
Any advice or suggestions would be much appreciated.
--Richard

Moving an object in the opposite direction to the cursor

I am trying to accomplish a simple task using a 2D graphics library called paperscript. I have a grid of dots and I would like to recalculate the position of those dots based on the position of the mouse cursor so that the dot is displaced from it's original position in the opposite direction that the mouse cursor is from the original position, and displaced by a distance that is inversely proportional to the distance of the mouse cursor to the original position. Hopefully this diagram makes it a little clearer:
I know how to get the current position of the mouse, as well as the position of each dot. What I have been having trouble with, is creating a function that will take those two variables and use it to calculate a new position for each dot that will create the above described effect.
I have a jsfiddle here with what I've created so far.
https://jsfiddle.net/yc62k/247xwh8q/4/
function onFrame(event) {
//Loop through all the dots
for (i = 0; i < count; i++) {
var item = project.activeLayer.children[i];
//Update the position of the dot based on the mouse position
??????
item.position = new Point(
(newPosition.x),
(newPosition.y)
);
}
}
Can anyone suggest an algorithm I can use in this function to get this effect? Or point me in the direction of the maths I would use to solve this problem? Any help would be greatly appreciated!
If the old position of the dot is pDot and the position of the mouse is pMouse, then the direction of movement is
dir = pDot - pMouse
To establish the desired scale (inversely proportional to the distance), just divide by the squared length. Then, the new position is:
pDotNew = pDot + dir * (1.0 / squaredLength(dir))
Be careful about how often you update the positions. If you update them very frequently, the points might move very fast. If this is the case, multiply the direction with a small number (between 0 and 1). Ideally, this number should depend on the update interval in order to maintain a consistent movement speed.

UrhoSharp - how to draw lines given points?

I'm trying to figure out how to draw shapes in UrhoSharp and I'm not getting anywhere with it. I thought it would be pretty straightforward. Searching the internet is not giving me much to go on.
All I want to do is give points so that I can draw lines between the points. 2-dimensional lines. So I can then draw shapes like a rectangle or triangle. I've looked at SkiaSharp, and drawing shapes is pretty straightforward, but for some reason, this concept seems foreign to UrhoSharp, at least from what I've looked at.
I've found a couple of code fragments where people are asking questions but I have no idea what else is going on aside from the bits that they show. If someone can point me to a reference that clearly explains how to do this, or show me here, I would really appreciate it.
Here is your example:
CustomGeometry geom = node.CreateComponent<CustomGeometry>();
geom.BeginGeometry(0, PrimitiveType.LineList);
var material = new Material();
material.SetTechnique(0, CoreAssets.Techniques.NoTextureUnlitVCol, 1, 1);
geom.SetMaterial(material);
float size = 1;
//x
geom.DefineVertex(Vector3.Zero);
geom.DefineColor(Color.Red);
geom.DefineVertex(Vector3.UnitX * size);
geom.DefineColor(Color.Red);
//y
geom.DefineVertex(Vector3.Zero);
geom.DefineColor(Color.Green);
geom.DefineVertex(Vector3.UnitY * size);
geom.DefineColor(Color.Green);
//z
geom.DefineVertex(Vector3.Zero);
geom.DefineColor(Color.Blue);
geom.DefineVertex(Vector3.UnitZ * size);
geom.DefineColor(Color.Blue);
geom.Commit();
Refer here for any future examples.

Align shape to vector using Dgame framework and D language

I've been using Dgame framework for simple simulations.
I need moving object to be aligned to their velocity vectors.
How is it possible to do that using Dgame?
I see that shape object has setRotation and setRotationCenter. Not sure how to use these to achieve the effect. I realize that default is rotation around origin. This causes objects to drift over time.
Sample code
struct GameObject {
Point **position;
// array of pointers to object points
Point *acceleration;
Point *velocity;
double max_speed;
double max_force;
}
shape = new Shape(Geometry.Quads,
Vertex(object.position[0].x, object.position[0].y),
Vertex(object.position[1].x, object.position[1].y),
Vertex(object.position[2].x, object.position[2].y),
Vertex(object.position[3].x, object.position[3].y))
// rotate shape to face velocity here
shape.move(object.velocity.x, object.velocity.y);
You can achieve this using atan2. Depending on the orientation of the texture you might need to change the values a bit or add 90/-90 degrees.
For textures that face up:
rotation = atan2(-velocity.x, velocity.y);
For textures that face right:
rotation = atan2(-velocity.y, -velocity.x);
You might need to convert the result from radians to degrees or the other way around.

transition a circle into a line by unrolling it with SVG and d3

For a project we are trying to make a circle into a line (and back again) while it is rotating along a linear path, much like a tire rotates and translates when rolling on a road, or a curled fore finger is extended and recurled into the palm.
In this Fiddle, I have a static SVG (the top circle) that rotates along the linear black path (which is above the circle, to mimic a finger extending) that is defined in the HTML.
I also use d3 to generate a "circle" that is made up of connected points (and can unfurl if you click on/in the circle thanks to #ChrisJamesC here ), and is translated and rotated
in the function moveAlongLine when you click on the purple Line:
function moveAlongLine() {
circle.data([lineData])
.attr("transform", "translate(78.5,0) rotate(-90, 257.08 70) ")
.duration(1000)
circle.on("click", transitionToCircle)
}
The first problem is that the .duration(1000) is not recognized and throws a Uncaught TypeError: Object [object Array] has no method 'duration' in the console, so there is a difference between the static definition of dur in SVG and dynamically setting it in JS/D3, but this is minor.
The other is should the transform attributes be abstracted from one another like in the static circle? in the static circle, the translate is one animation, and the rotation is another, they just have the same star and duration, so they animate together. How would you apply both in d3?
The challenge that I can not get, is how to let it unroll upwards(and also re-roll back), with the static point being the top center of the circle also being the same as the leftmost point on the line.
these seem better:
I should try to get the unfurl animation to occur while also rotating? This seems like it would need to be stepwise/sequential based...
Or Consider an octogon (defined as a path), and if it were to rotate 7 of the sides, then 6, then 5.... Do this for a rather large number of points on a polyhedron? (the circle only needs to be around 50 or so pixels, so 100 points would be more than enough) This is the middle example in the fiddle. Maybe doing this programmatically?
Or This makes me think of a different way: (in the case of the octogon), I could have 8 line paths (with no Z, just an additional closing point), and transition between them? Like this fiddle
Or anything todo with keyframes? I have made an animation in Synfig, but am unsure ho get it to SVG. The synfig file is at http://specialorange.org/filedrop/unroll.sifz if you can convert to SVG, but the xsl file here doesn't correctly convert it for me using xsltproc.
this seems really complicated but potential:
Define a path (likely a bézier curve with the same number of reference points) that the points follow, and have the reference points dynamically translate as well... see this for an concept example
this seems complicated and clunky:
Make a real circle roll by, with a growing mask in front of it, all while a line grows in length
A couple of notes:
The number of points in the d3 circle can be adjusted in the JS, it is currently set low so that you can see a bit of a point in the rendering to verify the rotation has occurred (much like the gradient is in the top circle).
this is to help students learn what is conserved between a number line and a circle, specifically to help learn fractions. For concept application, take a look at compthink.cs.vt.edu:3000 to see our prototype, and this will help with switching representations, to help you get a better idea...
I ended up using the same function that generates the circle as in the question, and did a bit of thinking, and it seemed like I wanted an animation that looked like a finger unrolling like this fiddle. This lead me to the math and idea needed to make it happen in this fiddle.
The answer is an array of arrays, with each nested array being a line in the different state, and then animate by interpolating between the points.
var circleStates = [];
for (i=0; i<totalPoints; i++){
//circle portion
var circleState = $.map(Array(numberOfPoints), function (d, j) {
var x = marginleft + radius + lineDivision*i + radius * Math.sin(2 * j * Math.PI / (numberOfPoints - 1));
var y = margintop + radius - radius * Math.cos(2 * j * Math.PI / (numberOfPoints - 1));
return { x: x, y: y};
})
circleState.splice(numberOfPoints-i);
//line portion
var lineState = $.map(Array(numberOfPoints), function (d, j) {
var x = marginleft + radius + lineDivision*j;
var y = margintop;
return { x: x, y: y};
})
lineState.splice(i);
//together
var individualState = lineState.concat(circleState);
circleStates.push(individualState);
}
and the animation(s)
function all() {
for(i=0; i<numberOfPoints; i++){
circle.data([circleStates[i]])
.transition()
.delay(dur*i)
.duration(dur)
.ease("linear")
.attr('d', pathFunction)
}
}
function reverse() {
for(i=0; i<numberOfPoints; i++){
circle.data([circleStates[numberOfPoints-1-i]])
.transition()
.delay(dur*i)
.duration(dur)
.ease("linear")
.attr('d', pathFunction)
}
}
(Note: This should be in comments but not enough spacing)
Circle Animation
Try the radial wipe from SO. Need to tweak it so angle starts at 180 and ends back at same place (line#4-6,19) and move along the X-axis (line#11) on each interation. Change the <path... attribute to suit your taste.
Line Animation Grow a line from single point to the length (perimeter) of the circle.
Sync both animation so that it appears good on all browsers (major headache!).

Resources