Shoot moving objects in 2D - c#

I have a 2d space with multiple objects(Lets call them B). Lets say object A our automated actor, he moves in a specific path and he has to shoot only the objects it can destroy. The other objects might or might not move.
I need to find the direction that I should fire the bullet that will collide with the object B. The bullet is moving with a different speed that object A and it has a specific lifetime.
I've tried to solve it with Quadratic but I always get infinity, is this a wrong approach?
Vector3 vectorFromVictim = bullet.Position - victim.Position;
float distanceToVictim = vectorFromVictim.Length();
double victimSpeed = victim.Position.Length();
double a = bulletSpeed * bulletSpeed - victimSpeed * victimSpeed;
double b = 2 * vectorFromVictim.Dot(victim.LinearVelocity);
double c = -distanceToVictim * distanceToVictim;
float t = (QuadraticSolver(a, b, c));
if (float.IsInfinity(t))
{
return;
}
interceptionPosition = victim.Position + victim.LinearVelocity * t;
if (t <= bulletLifetime)
{
ShootAtDirection(interceptionPosition);
}
Edit: My QuadraticSolver is this
double d = Math.Pow(b, 2) - (4 * a * c);
if (d < 0)
{
return float.PositiveInfinity;
}
float t;
if (d == 0)
{
t = (float) (-b / (2 * a));
if (float.IsNaN(t))
{
return float.PositiveInfinity;
}
return t;
}
t = (float) ((-b - Math.Sqrt(d)) / (2 * a));
float t2 = (float) ((-b + Math.Sqrt(d)) / (2 * a));
if (t < t2)
{
return t < 0 ? float.PositiveInfinity : t;
}
return t2 < 0 ? float.PositiveInfinity : t2;

B (target) coordinates are
bx + ux * t, by + uy * t
where ux, uy are components of B velocity vector
Bullet coordinates are
ax + v * cos(f) * t, ay + v * sin(f) * t
where v is bullet speed, f is directional angle (unknown yet)
ax + v * cos(f) * t = bx + ux * t
ay + v * sin(f) * t = y + uy * t
t * (v * cos(f) - ux) = bx - ax = dx
t * (v * sin(f) - uy) = bx - ax = dy
dx, dy is position difference, negated your vectorFromVictim
exclude t
dy * (v * cos(f) - ux) = dx * (v * sin(f) - uy)
dy * v * cos(f) - dy * ux = dx * v * sin(f) - dx * uy
v * (dy*cos(f) - dx*sin(f)) = dy * ux - dx * uy
let
g = atan2(dy, dx)
L = vectorFromVictim.Length
so
v * sin(g - f) = L * (dy * ux - dx * uy)
sin(g - f) = L/v * (dy * ux - dx * uy)
g - f = arcsin(L/v * (dy * ux - dx * uy) )
and finally
f = g - arcsin(L/v * (dy * ux - dx * uy) )
Quiclk Python test
import math
def aiming(ax, ay, bx, by, ux, uy, v):
dx = bx - ax
dy = by - ay
g = math.atan2(dy, dx)
L = math.hypot(dy, dx)
if (v * math.cos(ang) - ux):
t = dx / (v * math.cos(ang) - ux)
elif (v * math.sin(ang) - uy):
t = dy / (v * math.sin(ang) - uy)
else:
return None
coll_x = bx + ux * t
coll_y = by + uy * t
return ang, coll_x, coll_y
print(aiming(0, 0, 0, 1, 1, 0, 1.4142))
gives correct value 0.7854 = Pi/4 radians = 45 degrees, and point (1,1)

Related

Calculating polygon vertices with an angle produce the shape wrong size

When i call my funtion with a startingAngle=0 it produce a good shape with the correct size.
Example:
var points = GetPolygonVertices(sides:4, radius:5, center:(5, 5), startingAngle:0), produces:
points[0] = {X = 10 Y = 5}
points[1] = {X = 5 Y = 0}
points[2] = {X = 0 Y = 5}
points[3] = {X = 5 Y = 10}
As observed the side length is 10px, which is correct, but produce a rotated square at 45º from human eye prespective.
To fix this i added a switch/case to offset the startAngle so it will put the square at correct angle for human eye, by rotating 45º. The rotation works, but the shape is no longer a square of 10x10px, instead i lose 1 to 2px from sides:
[0] = {X = 9 Y = 1}
[1] = {X = 1 Y = 1}
[2] = {X = 1 Y = 9}
[3] = {X = 9 Y = 9}
and become worse as radius grow, for example with radius=10:
[0] = {X = 17 Y = 3}
[1] = {X = 3 Y = 3}
[2] = {X = 3 Y = 17}
[3] = {X = 17 Y = 17}
I tried with both floor and ceil instead of round, but it always end in lose 1 or 2px...
Is there a way to improve the function to keep the shape size equal no matter the number of sides and rotation angle?
My function:
public static Point[] GetPolygonVertices(int sides, int radius, Point center, double startingAngle = 0)
{
if (sides < 3)
throw new ArgumentException("Polygons can't have less than 3 sides...", nameof(sides));
// Fix rotation
switch (sides)
{
case 3:
startingAngle += 90;
break;
case 4:
startingAngle += 45;
break;
case 5:
startingAngle += 22.5;
break;
}
var points = new Point[sides];
var step = 360.0 / sides;
int i = 0;
for (var angle = startingAngle; angle < startingAngle + 360.0; angle += step) //go in a circle
{
if (i == sides) break; // Fix floating problem
double radians = angle * Math.PI / 180.0;
points[i++] = new(
(int) Math.Round(Math.Cos(radians) * radius + center.X),
(int) Math.Round(Math.Sin(-radians) * radius + center.Y)
);
}
return points;
}
EDIT: I updated the function to get rid of the switch condition and product shapes in correct orientation for human eye when angle is not given. Still it suffer from same "problem"
public static Point[] GetPolygonVertices(int sides, int radius, Point center, double startingAngle = 0, bool flipHorizontally = false, bool flipVertically = false)
{
if (sides < 3)
throw new ArgumentException("Polygons can't have less than 3 sides...", nameof(sides));
var vertices = new Point[sides];
double deg = 360.0 / sides;//calculate the rotation angle
var rad = Math.PI / 180.0;
var x0 = center.X + radius * Math.Cos(-(((180 - deg) / 2) + startingAngle) * rad);
var y0 = center.Y - radius * Math.Sin(-(((180 - deg) / 2) + startingAngle) * rad);
var x1 = center.X + radius * Math.Cos(-(((180 - deg) / 2) + deg + startingAngle) * rad);
var y1 = center.Y - radius * Math.Sin(-(((180 - deg) / 2) + deg + startingAngle) * rad);
vertices[0] = new(
(int) Math.Round(x0),
(int) Math.Round(y0)
);
vertices[1] = new(
(int) Math.Round(x1),
(int) Math.Round(y1)
);
for (int i = 0; i < sides - 2; i++)
{
double dsinrot = Math.Sin((deg * (i + 1)) * rad);
double dcosrot = Math.Cos((deg * (i + 1)) * rad);
vertices[i + 2] = new(
(int)Math.Round(center.X + dcosrot * (x1 - center.X) - dsinrot * (y1 - center.Y)),
(int)Math.Round(center.Y + dsinrot * (x1 - center.X) + dcosrot * (y1 - center.Y))
);
}
if (flipHorizontally)
{
var startX = center.X - radius;
var endX = center.X + radius;
for (int i = 0; i < sides; i++)
{
vertices[i].X = endX - (vertices[i].X - startX);
}
}
if (flipVertically)
{
var startY = center.Y - radius;
var endY = center.Y + radius;
for (int i = 0; i < sides; i++)
{
vertices[i].Y = endY - (vertices[i].Y - startY);
}
}
return vertices;
}
EDIT 2: From Tim Roberts anwser here the functions to calculate side length from radius and radius from side length, this solve my problem. Thanks!
public static double CalculatePolygonSideLengthFromRadius(double radius, int sides)
{
return 2 * radius * Math.Sin(Math.PI / sides);
}
public static double CalculatePolygonVerticalLengthFromRadius(double radius, int sides)
{
return radius * Math.Cos(Math.PI / sides);
}
public static double CalculatePolygonRadiusFromSideLength(double length, int sides)
{
var theta = 360.0 / sides;
return length / (2 * Math.Cos((90 - theta / 2) * Math.PI / 180.0));
}
Your problem is one of mathematics. You said "As observed, the side length is 10px". It very definitely is not 10px. The distance from (10,5) to (5,0) is sqrt(5*5 + 5*5), which is 7.07. That's exactly what we expect for a square that is inscribed in a circle of radius 5: 5 x sqrt(2).
And that's what the other squares are as well.
FOLLOWUP
As an added bonus, here is a function that returns the radius of the circle that circumscribes a regular polygon with N sides of length L:
import math
def rad(length,nsides):
theta = 360/nsides
r = length / (2 * math.cos( (90-theta/2) * math.pi / 180))
return r
for s in range(3,9):
print(s, rad(10,s))

Optimization of Loop of Large Points in Large Point Cloud

All I have the following implementation of a line detecting Hough transform for point clouds (collection of points in 3-space)
internal sealed class LineHoughTransform : ILineHoughTransform
{
private readonly double _dX;
private readonly double _maxX;
private readonly long _countX;
private readonly long _countB;
private readonly IDiscreetSphere _sphere;
public LineHoughTransform(Vector3 minParameterVector, Vector3 maxParameterVector, double dX, int sphereGranularity)
{
_dX = dX;
_sphere = new Icosahedron();
_sphere.Create(sphereGranularity);
_countB = _sphere.Points.Count;
_maxX = Math.Max(maxParameterVector.Norm(), minParameterVector.Norm());
var rangeX = 2 * _maxX;
if (_dX == 0.0)
_dX = rangeX / 64.0;
_countX = (long)(rangeX / _dX).RoundToNearest();
VotingSpace = new Dictionary<long, int>();
}
public int GetLine(ref Vector3 a, ref Vector3 b)
{
int votes = 0;
long index = 0;
foreach (var storedVote in VotingSpace)
{
if (storedVote.Value > votes)
{
votes = storedVote.Value;
index = storedVote.Key;
}
}
// Retrieve x' coordinate from VotingSpace[_countX * _countX * _countB].
double x = index / (_countX * _countB);
index -= (long)(x * _countX * _countB);
x = x * _dX - _maxX;
// Retrieve y' coordinate from VotingSpace[_countX * _countX * _countB].
double y = index / _countB;
index -= (long)y * _countB;
y = y * _dX - _maxX;
// Retrieve directional vector and Compute anchor point according to Eq. (3).
b = _sphere.Points[(int)index];
a.X = (float)(x * (1 - ((b.X * b.X) / (1 + b.Z))) - y * ((b.X * b.Y) / (1 + b.Z)));
a.Y = (float)(x * (-((b.X * b.Y) / (1 + b.Z))) + y * (1 - ((b.Y * b.Y) / (1 + b.Z))));
a.Z = (float)(-x * b.X - y * b.Y);
return votes;
}
public void Add(IPointCloud pointCloud)
{
CastVote(pointCloud, true);
}
public void Subtract(IPointCloud pointCloud)
{
CastVote(pointCloud, false);
}
private void CastVote(IPointCloud pointCloud, bool add)
{
if (pointCloud == null || pointCloud.Vertices == null)
return;
foreach (var vertex in pointCloud.Vertices)
PointVote(vertex.Point, add);
}
private void PointVote(Vector3 point, bool add)
{
// Loop over directions B.
for (int j = 0; j < _sphere.Points.Count; ++j)
{
// Denominator in Eq. (2).
Vector3 b = _sphere.Points[j];
double beta = 1 / (1 + b.Z);
// Compute x' and y' according to Eq. (2).
double newX = ((1 - (beta * (b.X * b.X))) * point.X) - (beta * (b.X * b.Y) * point.Y) - (b.X * point.Z);
double newY = (-beta * (b.X * b.Y) * point.X) + ((1 - (beta * (b.Y * b.Y))) * point.Y) - (b.Y * point.Z);
long x_i = (long)((newX + _maxX) / _dX).RoundToNearest();
long y_i = (long)((newY + _maxX) / _dX).RoundToNearest();
// Compute one-dimensional index from three indices.
// x_i * <number of planes> * <number of direction vectors> + y_i * <number of direction vectors> + <loop index>
long index = (x_i * _countX * _countB) + (y_i * _countB) + j;
if (!VotingSpace.ContainsKey(index))
VotingSpace.Add(index, 0);
if (add)
VotingSpace[index]++;
else
VotingSpace[index]--;
}
}
public Dictionary<long, int> VotingSpace { get; private set; }
}
I would like to improve the speed of this code, so I attempted to use
public ConcurrentDictionary<long, int> VotingSpace { get; private set; }
with
private void CastVote(IPointCloud pointCloud, bool add)
{
if (pointCloud == null || pointCloud.Vertices == null)
return;
Parallel.ForEach(pointCloud.Vertices, vertex => PointVote(vertex.Point, add));
}
Note, pointCloud in CastVote can contain vast numbers of points, and the VotingSpace incrementation becoming
if (!VotingSpace.ContainsKey(index))
VotingSpace.TryAdd(index, 0);
if (add)
VotingSpace[index]++;
else
VotingSpace[index]--;
However, sometimes the TryAdd is failing, causing my calling algorithm to fail. I have attempted to put a retry on the TryAdd but this does not seem to help the problem of dropped indexes. How can I make this class optimally multi-threaded, as simply as possible and working in exactly the same way as the original?
When working with concurrent collections, you normally use the special atomic APIs they offer. In this case you should probably use the ConcurrentDictionary.AddOrUpdate method:
VotingSpace.AddOrUpdate(index,
addValueFactory: (key) => add ? 1 : -1,
updateValueFactory: (key, existingValue) => existingValue + (add ? 1 : -1));

Problem with different outcome with DCT transformation on image while converting C++ to C#

I tried to write APP that would make DCT-2 transformation on image fragment and then transform back with inverse DCT-2. I have found code in c++/opencv that I tried to convert to C#, but somehow, I have different outcome at some point. Here is the code i tried to convert:
for (unsigned v = 0; v < BLOCK_SIZE; ++v)
{
for (unsigned u = 0; u < BLOCK_SIZE; ++u)
{
const double cu = (u == 0) ? 1.0 / sqrt(2) : 1.0;
const double cv = (v == 0) ? 1.0 / sqrt(2) : 1.0;
double dctCoeff = 0;
for (unsigned y = 0; y < BLOCK_SIZE; ++y)
{
for (unsigned x = 0; x < BLOCK_SIZE; ++x)
{
double uCosFactor = cos((double)(2 * x + 1) * M_PI * (double)u / (2 * (double) BLOCK_SIZE));
double vCosFactor = cos((double)(2 * y + 1) * M_PI * (double)v / (2 * (double) BLOCK_SIZE));
double pixel = (double)(lenaNoseGrey.at<unsigned char>(cv::Point(x,y)));
dctCoeff += pixel * uCosFactor * vCosFactor;
}
}
dctCoeff *= (2 / (double) BLOCK_SIZE) * cu * cv;
lenaNoseDct.at<double>(cv::Point(u,v)) = dctCoeff;
}
}
And here is mine:
for (int v = 0; v < BLOCK_SIZE; ++v)
{
for (int u = 0; u < BLOCK_SIZE; ++u)
{
double cu = (u == 0) ? 1.0 / Math.Sqrt(2) : 1.0;
double cv = (v == 0) ? 1.0 / Math.Sqrt(2) : 1.0;
double dctCoeff = 0;
double dctCoeffAlpha = 0;
for (int y1 = 0; y1 < BLOCK_SIZE; ++y1)
{
for (int x1 = 0; x1 < BLOCK_SIZE; ++x1)
{
double uCosFactor = Math.Cos((2 * x1 + 1) * Math.PI * u / (2 * (double)BLOCK_SIZE));
double vCosFactor = Math.Cos((2 * y1 + 1) * Math.PI * v / (2 * (double)BLOCK_SIZE));
double pixel = (double)bitmapaWy1.GetPixel((x1 + 284), (y1 + 313)).R;
double pixelalpha = (double)bitmapaWy1.GetPixel((x1 + 284), (y1 + 313)).A;
dctCoeff += pixel * uCosFactor * vCosFactor;
//dctCoeffAlpha += pixelalpha * uCosFactor * vCosFactor;
dctCoeffAlpha = pixelalpha;
}
}
dctCoeffAlpha *= (2 / (double)BLOCK_SIZE) * cu * cv;
dctCoeff *= (2 / (double)BLOCK_SIZE) * cu * cv;
macierz[u, v] = dctCoeff;
}
}
I have different outcome in my matrix, but when i convert matrix from the C++ code above with my inverse code, it works well.
Can you find what have I done wrong? One difference I can spot is with getpixel method, but it is performed on exact same grayscaled image and image fragment that C++ code was performed.
When i inverse my matrix to image again, I can see image, but it has lot of random pixels that are too white, or too black.
Problem is solved, the issue was too much code, actual code i posted works, problem was code I had after it, which was changing "dctcoeff" to byte and it was inside loop, so value of dct didnt reset to 0;
int BLOCK_SIZE = 16;
double[,] macierz = new double[16, 16];
for (int v = 0; v < BLOCK_SIZE; ++v)
{
for (int u = 0; u < BLOCK_SIZE; ++u)
{
double cu = (u == 0) ? 1.0 / Math.Sqrt(2) : 1.0;
double cv = (v == 0) ? 1.0 / Math.Sqrt(2) : 1.0;
double dctCoeff = 0;
for (int y1 = 0; y1 < BLOCK_SIZE; ++y1)
{
for (int x1 = 0; x1 < BLOCK_SIZE; ++x1)
{
double uCosFactor = Math.Cos((2 * x1 + 1) * Math.PI * u / (2 * (double)BLOCK_SIZE));
double vCosFactor = Math.Cos((2 * y1 + 1) * Math.PI * v / (2 * (double)BLOCK_SIZE));
double pixel = bitmapaWy1.GetPixel((x1 + 284), (y1 + 313)).R;
dctCoeff += pixel * uCosFactor * vCosFactor;
//dctCoeffAlpha += pixelalpha * uCosFactor * vCosFactor;
}
}
dctCoeff *= (2 / (double)BLOCK_SIZE) * cu * cv;
macierz[u, v] = dctCoeff;
}
}
This code works like a charm. I hope some good soul will use it, becouse i spent about 20h into making it work.
This is clearly a precision issue.
Most likely the problem is at the following line:
macierz[u, v] = dctCoeff;
I also have doubt in:
double pixel = (double)bitmapaWy1.GetPixel((x1 + 284), (y1 + 313)).R;
double pixelalpha = (double)bitmapaWy1.GetPixel((x1 + 284), (y1 + 313)).A;
dctCoeff += pixel * uCosFactor * vCosFactor;
//dctCoeffAlpha += pixelalpha * uCosFactor * vCosFactor;
dctCoeffAlpha = pixelalpha;

c# - Rotating Points About Axis

I currently have code that will generate segment points and at each segment point will generate some points within a short cylinder around the point (in 3D, the segments positions all have a z value of 0.0F (however I'd like to have varying z-values that are in a line - i.e. it's still in a line, but in the line z = 3x for example), but the x, and y are randomised). However currently all the points generated are in a cylinder that is facing upwards, I want to be able to rotate the points such that the cylinder they are 'generated' in is facing in the direction between the two segments. Here's an image of what it should look like vs. what it currently looks like
I found this similar question about rotating points around an axis; I took the answer and used that code for my RotatePoints() function but it doesn't seem to work correctly and I'm not sure why. Below is my psuedo code, what would I need to do get this function working correctly? Is there a better way to do this? The points just need to be generated within a rotated cylinder so would a completely different method be more efficient and easier?
All I have is the location of each segment and each point stored as a Vector3 {x,y,z} in local space.
Psuedo-Code
double radius;
// Generates the positions where the points will be generated around
// These are just the x,y,z positions of the object in world space
Vector3[] segmentLocations = GenerateSegmentPositions(numSegments);
for (int i = 0; i < numSegments; i++) {
// Generates points in a cylinder facing up the +ve y-axis
// This works fine
Vector3[][] pointsAroundSegment = GeneratePoints(segmentLocations[i], radius);
if (i != numSegments - 1 && i > 0) {
// Generate a normalise direction vector for the new direction
Vector3 newDir = Vector3.Normalise(segmentLocations[i + 1] - segmentLocations[i]);
double theta = Vector3.AngleBetween(newDir - Vector3.Normalise(segmentLocations[i] - segmentLocations[i - 1]));
// Rotates points (this currently rotates the points so they 'should' be facing the new direction, I haven't yet modified this to face the halfway point)
// This doesn't work
pointsAroundSegment = RotatePoints(pointsAroundSegment, newDir, theta/2);
} else if (i == numSegments - 1) {
// Generate final point
// This works fine
pointsAboutSegment = GenerateFinalPoint(segmentLocations[i]);
}
}
// This is the actual rotation function
// RotatePoints() effectively just calls this for each point in the array
public static double[] Rotate(double x, double y, double z, double u, double v, double w, double theta) {
double[] c = new double[3];
c [0] = u * (u * x + v * y + w * z) * (1 - Math.Cos (theta)) + x * Math.Cos (theta) + (-w * y + v * z) * Math.Sin (theta);
c [1] = v * (u * x + v * y + w * z) * (1 - Math.Cos (theta)) + y * Math.Cos (theta) + (w * x - u * z) * Math.Sin (theta);
c [2] = w * (u * x + v * y + w * z) * (1 - Math.Cos (theta)) + z * Math.Cos (theta) + (-v * x + u * y) * Math.Sin (theta);
return c;
}
Answer courtesy of Poosh;
To rotate the point (x,y,z) about the line through (a,b,c) with the normalised (u^2 + v^2 + w^2 = 1) direction vector by the angle theta use the following function:
public static double[] Rotate(double x, double y, double z, double a, double b, double c, double nu, double nv, double nw, double theta) {
double[] rP = new double[3];
rP [0] = (a * (nv * nv + nw * nw) - nu * (b * nv + c * nw - nu * x - nv * y - nw * z)) * (1 - Math.Cos (theta)) + x * Math.Cos (theta) + (-c * nv + b * nw - nw * y + nv * z) * Math.Sin (theta);
rP [1] = (b * (nu * nu + nw * nw) - nv * (a * nu + c * nw - nu * x - nv * y - nw * z)) * (1 - Math.Cos (theta)) + y * Math.Cos (theta) + (c * nu - a * nw + nw * x - nu * z) * Math.Sin (theta);
rP [2] = (c * (nu * nu + nv * nv) - nw * (a * nu + b * nv - nu * x - nv * y - nw * z)) * (1 - Math.Cos (theta)) + z * Math.Cos (theta) + (-b * nu + a * nv - nv * x + nu * y) * Math.Sin (theta);
return rP;
}

Get a parabola/arc based on vertex and a point

I'm trying to get a character to throw something in an arc at a target.
I know the vertex(x,y) and the target(x,y) and I want to get an arc from the origin(x,y) to the target with a max height of vertex.y
What I have is based off the vertex form of y = a(x-h)^2 + k
public static Vector3 parabola(Vector2 origin, Vector2 target, float height)
{
float dist = target.x - origin.x;
Vector2 vertex = new Vector2(origin.x + (dist / 2), origin.y + height);
//a = (y-k) / (x-h)^2
float a = (target.y - vertex.y) / ((target.x - vertex.x) * (target.x - vertex.x));
//b = (-h + -h) * a
float b = (-vertex.x + -vertex.x) * a;
//c = (h * h) * a + k
float c = (vertex.x * vertex.x) * a + vertex.y;
return new Vector3(a, b, c);
}
x += Time.DeltaTime;
float yPos = a * ((x - h) * (x - h)) + k;
This doesn't produce the correct arc. It's usually much too steep or much too shallow. Is my algebra wrong, or am I using the wrong approach?
Thanks
Here is a good solution: Wiki:Trajectory of a projectile.

Categories