Make a circle push others away? - c++

My problem is probably quite simple for you guys, I'm just new with programming so yeah.
I want to have a circle on the center of the screen, then I want that when a player gets close to it, he'll be pushed away in relation to the direction he came from,
Here's a little drawing I made to be abit more clear
The red circles are the player coming from different directions,
the green circle is the obstacle.
The arrows show what direction the player should be pushed to
the player moves only in the x,y axis
Thank you very much for your time

Transform player coordinates (red circle centres) from Descartes-like screen system to polar with origo of centre obstacle (green circle).
Choosing complex numbers for that purpose could be a solution: complex(x,y) == polar(r,th). Radii of objects are given and a tolerancy radius ('close') also.
Iterate through player coordinates and compare their magnitude (distance of red circle centres from origo). When distance is larger than sum of their radius + tolerancy then they are not considered close. Otherwise magnitudes are adjusted. Back transforming output coordinates into screen gives the result.
void PushAway( std::vector< std::complex< double > > & player_coords )
{
const double r_o = 3.0; // obstacle radius
const double r_p = 1.0; // player radius
const double r_t = 0.1; // 'close'
const double push = 10.0; // pushing amount
for( uint idx = 0; idx < player_coords.size(); ++idx )
{
std::complex< double > & pc = player_coords[idx];
double magn = std::abs( pc );
// too close ?
if( magn < r_o + r_t + r_p )
{
// push away in appropriate direction
pc = std::polar( push + magn, std::arg( pc ) );
}
}
}

Related

Fanning out an "arc" of card meshes

I have n number of cards. Each card is a units in width.
Many popular card games display a hand of cards in the "fanned out" position (see images below), and I would like to do the same. By utilizing the following formula, I'm able to place cards in an arc:
// NOTE: UE4 uses a left-handed, Z-up coordinate system.
// (+X = Forward, +Y = Right, and +Z = Up)
// NOTE: Card meshes have their pivot points in the center of the mesh
// (meshSize * 0.5f = local origin of mesh)
// n = Number of card meshes
// a = Width of each card mesh
const auto arcWidth = 0.8f;
const auto arcHeight = 0.15f;
const auto rotationAngle = 30.f;
const auto deltaAngle = 180.f;
const auto delta = FMath::DegreesToRadians(deltaAngle) / (float)(n);
const auto halfDelta = delta * 0.5f;
const auto halfMeshWidth = a * 0.5f;
const auto radius = halfMeshWidth + (rotationAngle / FMath::Tan(halfDelta));
for (unsigned y = 0; y < n; y++)
{
auto ArcX = (radius * arcWidth) * FMath::Cos(((float)y * delta) + halfDelta);
auto ArcY = (radius * arcHeight) * FMath::Sin(((float)y * delta) + halfDelta);
auto ArcVector = FVector(0.f, ArcX, ArcY);
// Draw a line from the world origin to the card origin
DrawDebugLine(GetWorld(), FVector::ZeroVector, ArcVector, FColor::Magenta, true, -1.f, 0, 2.5f);
}
Here's a 5-Card example from Hearthstone:
Here's a 5-Card example from Slay The Spire:
But the results I'm producing are, well... Suboptimal:
No matter how I tweak the variables, the cards on the far left and far right side are getting squashed together into the hand. I imagine this has to do with how the points of a circle are distributed, and then squashed downwards (via arcHeight) to form an ellipse? In any case, you can see that the results are far from similar, even though if you look closely at the example references, you can see that an arc exists from the center of each card (before those cards are rotated in local space).
What can I do to achieve a more evenly spaced arc?
Your distribution does look like an ellipse. What you need is a very large circle, where the center of the circle is way off the bottom of the screen. Something like the circle below, where the black rectangle is the screen area where you're drawing the cards, and the green dots are the card locations. Note that the radius of the circle is large, and the angles between the cards are small.

Calculating ball deflection angle when colliding with paddle in brick slayer game

Here is my code:
void Draw()
{
int x = 59;
int y = 500;
int temp = x;
int colour;
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 10; ++j)
{
if (i % 2 == 0)
colour = 2;
else
colour = 3;
DrawRectangle(x, y, 65, 25, colors[colour]);
x += 67;
}
x = temp;
y -= 39;
}
DrawRectangle(tempx, 0, 85, 12, colors[5]);
DrawCircle(templx, temply, 10, colors[7]);
}
// This function will be called automatically by this frequency: 1000.0 / FPS
void Animate()
{
templx +=5;
temply +=5;
/*if(templx>350)
templx-=300;
if(temply>350)
temply-=300;*/
glutPostRedisplay(); // Once again call the Draw member function
}
// This function is called whenever the arrow keys on the keyboard are pressed...
//
I am using OpenGL for this project. The function Draw() is used to print the bricks, slider, and the ball. The Animate() function is called automatically by the frequency given in the code. As it can be seen, I have incremented the values of templx and temply, but the ball goes out of screen as it crosses its limit. I have to deflect the ball if it collides with the paddle or the wall. What can I do to achieve this? All the conditions that I have used by now do not work properly.
So basically you would like to have a ball that is bouncing from the edges of your window. (For this answer I will ignore the slider, finding collision with the slider is very similar to finding collision with the walls).
templx and temply pair is position of your ball. I don't know what is the 3rd argument of DrawCircle function so I will assume that it is the radius. Let wwidth and wheight be width and height of a game window. Note that this magic constant 5 is, in fact, a velocity of the ball. Now ball is moving from upper left corner to lower right corner of your window. If you change 5 to -5 it will move from lower right corner to upper left corner.
Let's introduce two more variables vx and vy - velocity on x axis and velocity on y axis. The initial values will be 5 and 5. Now notice that when ball hits the right edge of the window it doesn't change its vertical velocity, it is still moving up/down but it changes its horizontal velocity from left->right to right->left. So if the vx was 5, after hitting the right edge of the window we should change it to -5.
The next problem is how to find out if we hit the edge of the window or not.
Note that the right-most point on the ball has the position templx + radius and the left-most point on the ball has the position templx - radius etc. Now to find out if we hit the wall or not we should just compare this values with window dimensions.
// check if we hit right or left edge
if (templx + radius >= wwidth || templx - radius <= 0) {
vx = -vx;
}
// check if we hit top or bottom edge
if (temply + radius >= wheight || temply - radius <= 0) {
vy = -vy;
}
// update position according to velocity
templx += vx;
temply += vy;

algorithm for drawing a sort of nozzle(line),whose is direction determined by the mouse?

i am using The old Turbo C++ and am a beginner.
This is the code of a ongoing project that i am planning.
the circle moves withe WSAD keys
But the problem is that i want the nozzle(a line from the center) of that circle to follow the movement of the mouse,but i cant figure out the mathematical part to restrict the length of that nozzle to, say 30 pixels. the line goes on touching the pointer's location.
I tried to use the Distance formula and the line equation to get with an expression which has both the slope and the length of the line. But the problem here is that there is an square root in the denominator, and i think that is causing the problem
Most of the code here is unnecessary for the following problem, so please ignore
here is the relevant code
originx=getmaxx()/2;
originy=getmaxy()/2;
while(doga==0) //main game loop
{ if(kbhit())
op=getch();
if(limiter>10) //limiter is used to restrict the motion of the circle for a limited // time
{ op=0;limiter=0;} // otherwise the cirlce moves in that direction unless another //key is pressed
//movement of the circle
if(op==72)
{ originy--; limiter++;}
if(op==80)
{originy++; limiter++;}
if(op==75)
{ originx--; limiter++ ;}
if(op==77)
{ originx++; limiter++; }
circle(originx,originy,5);
mouseposi(x,y,cl);
printf(" %d %d",x,y);
printf("\b\b\b\b\b\b\b\b");
m=sloper(originx,originy,x,y);
line(originx,originy,80/sqrt(1+m*m),m*80/sqrt(1+m*m)); //THIS LINE IS WHERE THE PROBLEM IS
delay(30);
cleardevice();
if(op==49) //for exiting
doga=2;
}
}
Let (x,y) be the point you're after, (ox, oy) be your origin, and (mx, my) be the mouse location.
The vector from the origin to the mouse is (dx, dy) = (mx - ox, my - oy).
The distance between the mouse and the origin is the same as the norm of that vector:
distance = sqrt(dx * dx + dy * dy);
Normalizing (scaling) the vector to get a new vector of length 1 ("unit length") we get
nx = dx / distance;
ny = dy / distance;
And finally we can scale those coordinates by the desired length (remembering to add back the origin)
x = ox + length * nx;
y = oy + length * ny;

Ray tracing vectors

So I decided to write a ray tracer the other day, but I got stuck because I forgot all my vector math.
I've got a point behind the screen (the eye/camera, 400,300,-1000) and then a point on the screen (a plane, from 0,0,0 to 800,600,0), which I'm getting just by using the x and y values of the current pixel I'm looking for (using SFML for rendering, so it's something like 267,409,0)
Problem is, I have no idea how to cast the ray correctly. I'm using this for testing sphere intersection(C++):
bool SphereCheck(Ray& ray, Sphere& sphere, float& t)
{ //operator * between 2 vec3s is a dot product
Vec3 dist = ray.start - sphere.pos; //both vec3s
float B = -1 * (ray.dir * dist);
float D = B*B - dist * dist + sphere.radius * sphere.radius; //radius is float
if(D < 0.0f)
return false;
float t0 = B - sqrtf(D);
float t1 = B + sqrtf(D);
bool ret = false;
if((t0 > 0.1f) && (t0 < t))
{
t = t0;
ret = true;
}
if((t1 > 0.1f) && (t1 < t))
{
t = t1;
ret = true;
}
return ret;
}
So I get that the start of the ray would be the eye position, but what is the direction?
Or, failing that, is there a better way of doing this? I've heard of some people using the ray start as (x, y, -1000) and the direction as (0,0,1) but I don't know how that would work.
On a side note, how would you do transformations? I'm assuming that to change the camera angle you just adjust the x and y of the camera (or the screen if you need a drastic change)
The parameter "ray" in the function,
bool SphereCheck(Ray& ray, Sphere& sphere, float& t)
{
...
}
should already contain the direction information and with this direction you need to check if the ray intersects the sphere or not. (The incoming "ray" parameter is the vector between the camera point and the pixel the ray is sent.)
Therefore the local "dist" variable seems obsolete.
One thing I can see is that when you create your rays you are not using the center of each pixel in the screen as the point for building the direction vector. You do not want to use just the (x, y) coordinates on the grid for building those vectors.
I've taken a look at your sample code and the calculation is indeed incorrect. This is what you want.
http://www.csee.umbc.edu/~olano/435f02/ray-sphere.html (I took this course in college, this guy knows his stuff)
Essentially it means you have this ray, which has an origin and direction. You have a sphere with a point and a radius. You use the ray equation and plug it into the sphere equation and solve for t. That t is the distance between the ray origin and the intersection point on the spheres surface. I do not think your code does this.
So I get that the start of the ray would be the eye position, but what is the direction?
You have camera defined by vectors front, up, and right (perpendicular to each other and normalized) and "position" (eye position).
You also have width and height of viewport (pixels), vertical field of view (vfov) and horizontal field of view (hfov) in degrees or radians.
There are also 2D x and y coordinates of pixel. X axis (2D) points to the right, Y axis (2D) points down.
For a flat screen ray can be calculated like this:
startVector = eyePos;
endVector = startVector
+ front
+ right * tan(hfov/2) * (((x + 0.5)/width)*2.0 - 1.0)
+ up * tan(vfov/2) * (1.0 - ((y + 0.5f)/height)*2.0);
rayStart = startVector;
rayDir = normalize(endVector - startVector);
That assumes that screen plane is flat. For extreme field of view angles (fov >= 180 degreess) you might want to make screen plane spherical, and use different formulas.
how would you do transformations
Matrices.

3d model to fit in viewport

How does a 3D model handled unit wise ?
When i have a random model that i want to fit in my view port i dunno if it is too big or not, if i need to translate it to be in the middle...
I think a 3d object might have it's own origine.
You need to find a bounding volume, a shape that encloses all the object's vertices, for your object that is easier to work with than the object itself. Spheres are often used for this. Either the artist can define the sphere as part of the model information or you can work it out at run time. Calculating the optimal sphere is very hard, but you can get a good approximation using the following:
determine the min and max value of each point's x, y and z
for each vertex
min_x = min (min_x, vertex.x)
max_x = max (max_x, vertex.x)
min_y = min (min_y, vertex.y)
max_y = max (max_y, vertex.y)
min_z = min (min_z, vertex.z)
max_z = max (max_z, vertex.z)
sphere centre = (max_x + min_x) / 2, (max_y + min_y) / 2, (max_z + min_z) / 2
sphere radius = distance from centre to (max_x, max_y, max_z)
Using this sphere, determine the a world position that allows the sphere to be viewed in full - simple geometry will determine this.
Sorry, your question is very unclear. I suppose you want to center a 3D model to a viewport. You can achieve this by calculating the model's bounding box. To do this, traverse all polygons and get the minimum/maximum X/Y/Z coordinates. The bounding box given by the points (min_x,min_y,min_z) and (max_x,max_y,max_z) will contain the whole model. Now you can center the model by looking at the center of this box. With some further calculations (depending on your FOV) you can also get the left/right/upper/lower borders inside your viewport.
"so i tried to scale it down"
The best thing to do in this situation is not to transform your model at all! Leave it be. What you want to change is your camera.
First calculate the bounding box of your model somewhere in 3D space.
Next calculate the radius of it by taking the max( aabb.max.x-aabb.min.x, aabb.max.y-aabb.min.y, aabb.max.z-aabb.min.z ). It's crude but it gets the job done.
To center the object in the viewport place the camera at the object position. If Y is your forward axis subtract the radius from Y. If Z is the forward axis then subtract radius from it instead. Subtract a fudge factor to get you past the pesky near plane so your model doesn't clip out. I use quaternions in my engine with a nice lookat() method. So call lookat() and pass in the center of the bounding box. Voila! You're object is centered in the viewport regardless of where it is in the world.
This always places the camera axis aligned so you might want to get fancy and transform the camera into model space instead, subtract off the radius, then lookat() the center again. Then you're always looking at the back of the model. The key is always the lookat().
Here's some example code from my engine. It checks to see if we're trying to frame a chunk of static terrain, if so look down from a height, or a light or a static mesh. A visual is anything that draws in the scene and there are dozens of different types. A Visual::Instance is a copy of the visual, or where to draw it.
void EnvironmentView::frameSelected(){
if( m_tSelection.toInstance() ){
Visual::Instance& I = m_tSelection.toInstance().cast();
Visual* pVisual = I.toVisual();
if( pVisual->isa( StaticTerrain::classid )){
toEditorCamera().toL2W().setPosition( pt3( 0, 0, 50000 ));
toEditorCamera().lookat( pt3( 0 ));
}else if( I.toFlags()->bIsLight ){
Visual::LightInstance& L = static_cast<Visual::LightInstance&>( I );
qst3& L2W = L.toL2W();
const sphere s( L2W.toPosition(), L2W.toScale() );
const f32 y =-(s.toCenter()+s.toRadius()).y();
const f32 z = (s.toCenter()+s.toRadius()).y();
qst3& camL2W = toEditorCamera().toL2W();
camL2W.setPosition(s.toCenter()+pt3( 0, y, z ));//45 deg above
toEditorCamera().lookat( s.toCenter() );
}else{
Mesh::handle hMesh = pVisual->getMesh();
if( hMesh ){
qst3& L2W = m_tSelection.toInstance()->toL2W();
vec4x4 M;
L2W.getMatrix( M );
aabb3 b0 = hMesh->toBounds();
b0.min = M * b0.min;
b0.max = M * b0.max;
aabb3 b1;
b1 += b0.min;
b1 += b0.max;
const sphere s( b1.toSphere() );
const f32 y =-(s.toCenter()+s.toRadius()*2.5f).y();
const f32 z = (s.toCenter()+s.toRadius()*2.5f).y();
qst3& camL2W = toEditorCamera().toL2W();
camL2W.setPosition( L2W.toPosition()+pt3( 0, y, z ));//45 deg above
toEditorCamera().lookat( b1.toOrigin() );
}
}
}
}