Structured array in csharp? - c#

I have the following C++ code that i want to translate to C#
But i'm stuck in the definition of "Element" which is a structured array.
What is best to use ?
var list = new List<KeyValuePair<string, int>>();
for (i = 0; i< 8; i++)
{
Ixx += Element[i].vLocalInertia.x + Element[i].fMass * (Element[i].vCGCoords.y*Element[i].vCGCoords.y + Element[i].vCGCoords.z*Element[i].vCGCoords.z);
Iyy += Element[i].vLocalInertia.y + Element[i].fMass * (Element[i].vCGCoords.z*Element[i].vCGCoords.z + Element[i].vCGCoords.x*Element[i].vCGCoords.x);
Izz += Element[i].vLocalInertia.z + Element[i].fMass * (Element[i].vCGCoords.x*Element[i].vCGCoords.x + Element[i].vCGCoords.y*Element[i].vCGCoords.y);
Ixy += Element[i].fMass * (Element[i].vCGCoords.x * Element[i].vCGCoords.y);
Ixz += Element[i].fMass * (Element[i].vCGCoords.x * Element[i].vCGCoords.z);
Iyz += Element[i].fMass * (Element[i].vCGCoords.y * Element[i].vCGCoords.z);
}
And have the following type struct :
typedef struct _RigidBody {
float fMass; // total mass (constant)
Matrix3x3 mInertia; // mass moment of inertia in body coordinates (constant)
Matrix3x3 mInertiaInverse;// inverse of mass moment of inertia matrix (constant)
Vector vPosition; // position in earth coordinates
Vector vVelocity; // velocity in earth coordinates
Vector vVelocityBody; // velocity in body coordinates
Vector vAngularVelocity;// angular velocity in body coordinates
Vector vEulerAngles; // Euler angles in body coordinates
float fSpeed; // speed (magnitude of the velocity)
Quaternion qOrientation; // orientation in earth coordinates
//Matrix3x3 mRotation; // rotation matrix
Vector vForces; // total force on body
Vector vMoments; // total moment (torque) on body
Matrix3x3 mIeInverse; // inverse of moment of inertia in earth coordinates
} RigidBody, *pRigidBody;
typedef struct _BodyElement {
float fMass;
Vector vDCoords;
Vector vCGCoords;
Vector vLocalInertia;
float fIncidence;
float fDihedral;
Vector vNormal;
float fArea;
int iFlap;
} BodyElement, *pBodyElement;

Something like this?
public struct Element
{
public struct coord
{
public int x;
public int y;
public int z;
}
public coord vLocalIntetia;
public int fMass;
public coord vCGCoords;
}
Element[] element = new Element[8];
EDIT
Or this (with your added detail)
public struct BodyElement
{
float fMass;
Vector vDCoords;
Vector vCGCoords;
Vector vLocalInertia;
float fIncidence;
float fDihedral;
Vector vNormal;
float fArea;
int iFlap;
}
BodyElement[] element = new BodyElement[8];

Related

Rotate object in Unity 2D

Help to understand the management of objects. At the moment, there is a rotation of the object. I want the arrow to rotate, and the angle of rotation depends on the current X and Y coordinates. Unity2D.
Now it is left (does not rotate), but it needs to be right (it always rotates and looks in one direction), but I don’t know how to calculate the degrees for rotation.
`
public float angle = 0; // угол
public float radius = 0.5f; // радиус
public bool isCircle = false; // условие движения по кругу
public float speed = 5f;
// Update is called once per frame
void Update()
{
angle += Time.deltaTime; // меняется значение угла
var x = Mathf.Cos(angle * speed) * radius + parent.position.x;
var y = Mathf.Sin(angle * speed) * radius + parent.position.y;
transform.position = new Vector3(x, y,0);
//transform.Rotate(0, 0, a);
}
`
Help me, how to calculate angle?
You need Mathf.Atan2, it will return a radian, then you need to multiply a Mathf.Rad2Deg to get the Euler angle.

Given world position and normalized world space compute 2D canvas location

I am trying to create a F1 2021 Radar like shown in the repository here: https://github.com/ryry6/f1-radar-releases
Or in the image here
I have computed the delta X and Z coordinates to each of the cars, however I am struggling to get the cars to appear as intended on a 2D Canvas (C#, WPF).
The following is the data provided by the game:
public float m_worldPositionX; // World space X position
public float m_worldPositionY; // World space Y position
public float m_worldPositionZ; // World space Z position
public float m_worldVelocityX; // Velocity in world space X
public float m_worldVelocityY; // Velocity in world space Y
public float m_worldVelocityZ; // Velocity in world space Z
public short m_worldForwardDirX; // World space forward X direction (normalised)
public short m_worldForwardDirY; // World space forward Y direction (normalised)
public short m_worldForwardDirZ; // World space forward Z direction (normalised)
public short m_worldRightDirX; // World space right X direction (normalised)
public short m_worldRightDirY; // World space right Y direction (normalised)
public short m_worldRightDirZ; // World space right Z direction (normalised)
public float m_gForceLateral; // Lateral G-Force component
public float m_gForceLongitudinal; // Longitudinal G-Force component
public float m_gForceVertical; // Vertical G-Force component
public float m_yaw; // Yaw angle in radians
public float m_pitch; // Pitch angle in radians
public float m_roll; // Roll angle in radians
The following is the code I am unsure about...
var deltaX = PlayerCar.m_worldPositionX - OtherCar.m_worldPositionX;
var deltaZ = PlayerCar.m_worldPositionZ - OtherCar.m_worldPositionZ;
var deltaYawRad = PlayerCar.m_yaw - OtherCar.m_yaw;
// Convert from RAD to DEG
double deltaYaw = (180 / Math.PI) * deltaYawRad;
// This is the part I need help with
var moveUp = deltaZ * worldRightDirZ + deltaX * worldForwardDirX;
var moveLeft = deltaX * worldRightDirX + deltaZ * worldForwardDirZ;
// Set the rectangle to a position on the canvas and scale it accordingly
Canvas.SetTop(rec, RadarModel.PlayerCarTop + moveUp * RadarModel.Scale);
Canvas.SetLeft(rec, RadarModel.PlayerCarLeft + moveLeft * RadarModel.Scale);

How to find a position, knowing a direction, angle and distance?

Using the diagram provided, I know:
Character at position A, facing B (posA)
Object at position B (posB), facing a random direction.
desired angle (20) for C (desiredAngle), based in the direction A to B.
distance from B to C
How would I go about finding the position of C?
In the code below, I managed to get the vector BC, now how can define a point along that vector using the distance from A to B?
//The angle of the hand in relation to the object
public float angleFromPlayer = -60f;
//Get the direction vector from the selectedObject to the actor
Vector3 objectDirectionToActor = actorParent.position - selectedObjectCenter;
//Make it horizontal (Flatten the y)
objectDirectionToActor.y = 0;
//Get the rotated vector using the desiredAngle
Vector3 rotatedVector = Quaternion.Euler(0, angleFromPlayer, 0) * objectDirectionToActor;
Figured it out, here is the solution for posterity:
//How high the hand will be from the dropSurface/selectedObjectPivot
public float handOffsetFromDropSurface = 0.15f;
//The angle of the hand in relation to the object
public float targetAngleFromPlayer = -80f;
//Extra distance between selectedObjectCenter and wristBone (since the handDistance is a bit too short)
public float extraHandDistance = 0f;
Vector3 GetHandBonePositionForDropSurface(Vector3 selectedObjectCenter) {
//Get the direction vector from the selectedObject to the actor
Vector3 objectDirectionToActor = actorParent.position - selectedObjectCenter;
//Make it horizontal (Flatten the y)
objectDirectionToActor.y = 0;
//Change vector size to 1 for multiplication
objectDirectionToActor.Normalize();
//Get the rotated vector using the desiredAngle
Vector3 rotatedVector = Quaternion.Euler(0, targetAngleFromPlayer, 0) * objectDirectionToActor;
//Get the distance we want the point to be from the center of the selectedObject
float handDistance =
Vector3.Distance(playerProperties.boneRightIndexProximal.position,
playerProperties.boneRightHand.position) + extraHandDistance;
//Resize vector to match the hand distance
rotatedVector *= handDistance;
//Get finalPosition, adding the handOffsetFromDropSurface
Vector3 wristTargetPosition = selectedObjectCenter + rotatedVector + (Vector3.up * handOffsetFromDropSurface);
return wristTargetPosition;
}

Finding Circle-Line collision (as points, not bools) C#

So unlike everyone here, I'm trying to find the intersections from circle-line collision.
The points are taken from the user input.
float cx; //circle center x
float cy; //circle center y
float px; //point x
float py; //point y
float vx; //vector x
float vy; //vector y
float vySq = vy * vy;
float vxSq = vx * vx;
float cxSq = cx * cx;
float rSq = r * r;
float thatPart = ( ( (vy * px) / vx) + py - cy); //so I don't have to re-type it 3 different times
float a = 1 + (vySq/vxSq);
float b = (2 * cx) + ( (2 * vy) * thatPart / vx);
float c = cxSq + ( thatPart * thatPart ) - rSq;
float x1 = QUADRATIC(a, b, c, true);
float x2 = QUADRATIC(a, b, c, false);
float y1 = ((vy * x1) - (vy * px) + (vx * py)) / vx;
float y2 = ((vy * x2) - (vy * px) + (vx * py)) / vx;
My QUADRATIC function 100% works, so I am not worried about that.
It's a, b, and c. I receive the wrong values for them. And all this math is based on a pdf given in math class. (here)
So... what am I doing wrong?
Thanks.
The equations in both the PDF and the source code seem unnecessarily complicated, so I will re-establish them in a clenear way (or at least one that pleases me).
The vector from the center of the circle to any point S on the line can be written as
CS = CP + t V
where t is an arbitrary parameter.
S belongs to the circle when
CS² = R² = (CP + t V)²
giving the quadratic equation in t:
V² t² + 2 CP.V t + CP² - R² = 0
When you have the values of t, plug in the first equation.
Math Treatment
You have a line with coordinates (x,y) = (px + vx*t, py + vy*t) where t is an arbitrary parameter.
The line intersects the circle when its coordinates solve x^2 + y^2 = r^2.
This leads to the following quadratic equation, to be solved for t.
t^2 + 2*t*b + a = 0
a = (px^2+py^2-r^2)/(vx^2+vy^2)
b = (px*vx+py*vy)/(vx^2+vy^2)
The two solutions are:
t = -b ± sqrt(b^2-a)
Use the two t values into (x,y) to get the coordinates.
Sample Code
static class Program
{
static void Main(string[] args)
{
var ray = new Ray() {
Point = new Vector2(-3, 1),
Direction = new Vector2(2, 0.5f)
};
var circle = new Circle
{
Center = new Vector2(1, 1),
Radius = 4
};
var points = Geometry.Intersect(circle, ray);
if(points.Length>0)
{
foreach(var point in points)
{
Console.WriteLine(point.ToString());
}
}
else
{
Console.WriteLine("Circle and Ray do not intersect");
}
}
}
Object Oriented Models
public class Circle
{
public Vector2 Center { get; set; }
public float Radius { get; set; }
}
public class Ray
{
public Vector2 Point { get; set; }
public Vector2 Direction { get; set; }
public Vector2 Along(float t)
{
return Point + t*Direction;
}
}
public static class Geometry
{
public static Vector2[] Intersect(Circle circle, Ray ray)
{
float a = (ray.Point.LengthSquared()-circle.Radius*circle.Radius)/ray.Direction.LengthSquared();
float b = Vector2.Dot(ray.Point, ray.Direction)/ray.Direction.LengthSquared();
if(b*b-a>0)
{
// two intersection points
float t1 = -b-(float)Math.Sqrt(b*b-a);
float t2 = -b+(float)Math.Sqrt(b*b-a);
return new Vector2[] {
ray.Along(t1),
ray.Along(t2),
};
}
else if(b*b-a==0)
{
// one intersection point
float t = -b;
return new Vector2[] { ray.Along(t) };
}
else
{
// no intersection, return empty array
return new Vector2[0];
}
}
}
NOTE: Code uses System.Numerics library

Stuck with collision detection in circle pong in xna

I am making clone of Circle pong game in xna. I am not able to get collision of rotating pad with ball. I can't use farseer physics in this game as it is in mono game.
I found one method for it but it also not seem to work.
private void EllasticCollisionPhysics(Ball ball, GoScreen pad)
{
//find normal vector
Vector2 normal = new Vector2(pad.padV.X - ball.ballRectangle.X, pad.padV.Y - ball.ballRectangle.Y);
//find normal vector's modulus, i.e. length
float normalmod = (float)Math.Sqrt(Math.Pow(normal.X, 2) + Math.Pow(normal.Y, 2));
//find unitnormal vector
Vector2 unitnormal = new Vector2((pad.padV.X - ball.ballRectangle.X) / normalmod, (pad.padV.Y - ball.ballRectangle.Y) / normalmod);
//find tangent vector
Vector2 unittan = new Vector2(-1 * unitnormal.Y, unitnormal.X);
//first ball normal speed before collision
float inormalspeedb = unitnormal.X * velocity.X + unitnormal.Y * velocity.Y;
//first ball tangential speed
float itanspeed = unittan.X * velocity.X + unittan.Y * velocity.Y;
//Calculate normal speeds after the collision
//Calculate first ball Velocity vector components (tangential and normal)
Vector2 inormala = new Vector2(unitnormal.X * inormalspeedb, unitnormal.Y * inormalspeedb);
Vector2 itana = new Vector2(unittan.X * itanspeed, unittan.Y * itanspeed);
//Add Vector components to each balls' Velocity
velocity = Vector2.Add(inormala, itana);
You don't need farseer physics for that, what you need is circle to rectangle collisition funciton.
// circle is object with x,y,r parameters
bool intersects(CircleType circle, RectType rect)
{
circleDistance.x = abs(circle.x - rect.x);
circleDistance.y = abs(circle.y - rect.y);
if (circleDistance.x > (rect.width/2 + circle.r)) { return false; }
if (circleDistance.y > (rect.height/2 + circle.r)) { return false; }
if (circleDistance.x <= (rect.width/2)) { return true; }
if (circleDistance.y <= (rect.height/2)) { return true; }
cornerDistance_sq = (circleDistance.x - rect.width/2)^2 +
(circleDistance.y - rect.height/2)^2;
return (cornerDistance_sq <= (circle.r^2));
}
Added CircleType and RectType
public class CircleType
{
public int x;
public int y;
public decimal r;
}
public class RectType
{
public int x;
public int y;
public int width;
public int height;
}

Categories