Make Objects Follow Mouse - c++

Other questions close to this topic don't seem to help me understand it very much. I'm just starting programming using Visual Studio and Direct2D and I'm having trouble understanding how to make two "eyes," which are ellipses inside of ellipses, follow my mouse.
Inside of the function void MainWindow::CalculateLayout() I'm using
const float radius3=radius/4;
const float radius3_2=radius/5;
const float x3=x-100;
const float y3=y-150;
ellipse3 = D2D1::Ellipse(D2D1::Point2F(x3, y3), radius3, radius3_2);
//left eye
const float radius4=radius/4;
const float radius4_2=radius/5;
const float x4=x+100;
const float y4=y-150;
ellipse4 = D2D1::Ellipse(D2D1::Point2F(x4, y4), radius4, radius4_2);
//right eye
const float radius5=radius/8;
const float radius5_2=radius5/2;
const float x5=x-100;
const float y5=y-150;
ellipse5 = D2D1::Ellipse(D2D1::Point2F(x5, y5), radius5, radius5_2);
// left eyeball
const float radius6=radius/8;
const float radius6_2=radius6/2;
const float x6=x+100;
const float y6=y-150;
ellipse6 = D2D1::Ellipse(D2D1::Point2F(x6, y6), radius6, radius6_2);
// right eyeball
to set up where the eyes and eyeballs are. I think that something along the line of this should be used to control where the mouse is. I am trying to do this from a blank project, not from a form. Is the solution to simply replace const float x5=x-100 with the X value of MouseMove?

You need to replace the definition of x5, but you need to do it with a formula which will bound it to stay within the eyeball.
Your formula will look something like this:
// compute the angle from the eyes to the mouse
angle = arctan( (mouseY - y) / (mouseX - x) );
// x-100 and y-150 are assumed to be the origins (center) of the eyeball
// eyeballRadius should be the radius of the eyeball, or slightly smaller (so the eyes do not extend outside of it)
x5 = (x-100) + cos(angle) * eyeballRadius;
y5 = (y-150) + sin(angle) * eyeballRadius;
Hope this helps.
To get the cross-eyed effect when the cursor is very near, you should have each eyeball compute its own angle, for example the left's would be leftAngle = arctan( (mouseY - (y-150)) / (mouseX - (x-100)) )

Related

c++ Sfml trying to move an object to the Mouse Location by a particular amount every frame

Im kind of stuck with this problem
i created this function but for some reason i can only move the object to the right of the Player.
If i try to move the object to the Left of the Player is goes right.
here is my approach:
int Speed = 8;
int x = Player_x - Mouse_x;
int y = Player_y - MOuse_y;
float deg = atan(y / x);
float erg_x = Speed * cos(deg);
float erg_y = Speed * sin(deg);
erg_x/y are the numbers i use at the end to move the Object.
Please help me :)
As explained here, atan only works in the first and fourth quadrant. Since going left involves the second quadrant, this isn't going to work.
As such, you'll want to change
float deg = atan(y / x);
to
float deg = atan2(y, x);

Ray tracing - refraction bug

I am writing a ray tracer. So far I have diffuse, Blinn lighting and reflections. Something has gone wrong with my refractions and I have no idea what. I'm hoping someone can help me out.
I have a big red diffuse + Blinn sphere and a small refractive one with refraction index n = 1.5.
The small one is just really screwed up.
Relevant code:
ReflectiveSurface::ReflectiveSurface(const Color& _n, const Color& _k) :
F0(Color(((_n - 1)*(_n - 1) + _k * _k) / ((_n + 1)*(_n + 1) + _k * _k))) {}
Color ReflectiveSurface::F(const Point& N, const Point& V) const {
float cosa = fabs(N * V);
return F0 + (F0 * (-1) + 1) * pow(1 - cosa, 5);
}
Color ReflectiveSurface::getColor(const Incidence& incidence, const Scene& scene, int traceDepth) const {
Point reflectedDir = reflect(incidence.normal, incidence.direction);
Ray ray = Ray(incidence.point + reflectedDir * epsilon, reflectedDir);
return F(incidence.normal, incidence.direction) * scene.rayTrace(ray, traceDepth + 1);
}
Point ReflectiveSurface::reflect(const Point& N, const Point& V) const {
return V - N * (2 * (N * V));
}
bool RefractiveSurface::refractionDir(Point& T, Point& N, const Point& V) const {
float cosa = -(N * V), cn = n;
if (cosa < 0) { cosa = -cosa; N = N * (-1); cn = 1 / n; }
float disc = 1 - (1 - cosa * cosa) / cn / cn;
if (disc < 0) return false;
T = V / cn + N * (cosa / cn - sqrt(disc));
return true;
}
RefractiveSurface::RefractiveSurface(float _n, const Color& _k) : ReflectiveSurface(Color(1, 1, 1) * _n, _k) {}
Surface* RefractiveSurface::copy() { return new RefractiveSurface(*this); }
Color RefractiveSurface::getColor(const Incidence& incidence, const Scene& scene, int traceDepth) const {
Incidence I = Incidence(incidence);
Color reflectedColor, refractedColor;
Point direction = reflect(I.normal, I.direction);
Ray reflectedRay = Ray(I.point + direction * epsilon, direction);
if (refractionDir(direction, I.normal, I.direction)) {
Ray refractedRay = Ray(I.point + direction * epsilon, direction);
Color colorF = F(I.normal, I.direction);
reflectedColor = colorF * scene.rayTrace(reflectedRay, traceDepth + 1);
refractedColor = (Color(1, 1, 1) - colorF) * scene.rayTrace(refractedRay, traceDepth + 1);
}
else {
reflectedColor = scene.rayTrace(reflectedRay, traceDepth + 1);
}
return reflectedColor + refractedColor;
}
The code is all over the place, since this is a homework and I'm not allowed to include additional headers and I have to send it in in one cpp file, so i had to separate every class into forward declaration, declaration and implementation in that one file. It makes me vomit but I tried to keep it as clean as possible. There is tons of code so I only included what I thought was most related. ReflectiveSurface is RefractiveSurface's parent class. N is the surface normal, V is the ray direction vector this normal, n is the refraction index. The incidence structure holds a point, a normal and a direction vector.
Formulas for the Fersnel approximation and the refraction vector respectively:
You can see in the code that I use an epsilon * ray direction value to avoid shadow acne caused by float imprecision. Something similar seems to be happening to the small sphere, though.
Another screenshot:
As you can see, the sphere doesn't appear transparent, but it does inherit the diffuse sphere's color. It also usually has some white pixels.
Without refraction:
RefractiveSurface::refractionDir takes the normal N by (non-const) reference, and it may invert it. This seems dangerous. It's not clear the caller wants I.normal to be flipped, as it's used in color calculations further down.
Also, refracted_color is not always initialized (unless the Color constructor makes it black).
Try (temporarily) simplifying and just see if the refracted rays hit where you expect. Remove the Fresnel computation and the reflection component and just set refracted_color to the result of the trace of the refracted ray. That will help determine if the bug is in the Fresnel calculation or in the geometry of bending the ray.
A debugging tip: Color the pixels that don't hit anything with something other than black. That makes it easy to distinguish the misses from the shadows (surface acne).
The answer turned out to be pretty simple, but it took me like 3 days of staring at the code to catch the bug. I have a Surface class, I derive from it two classes: RoughSurface (diffuse+blinn) and RelfectiveSurface. Then, RefractiveSurace is derived from RefleciveSurface. ReflectiveSurface's constructor takes the refractive index(n) and the extinction value (k) as parameters, but doesn't store them. (F0) is computed from them during construction, and then they are lost. RefractiveSurface, on the other hand, uses (n) in the refraction angle calculation.
Old constructor:
RefractiveSurface::RefractiveSurface(float _n, const Color& _k) :
ReflectiveSurface(Color(1, 1, 1) * _n, _k) {}
New Constructor:
RefractiveSurface::RefractiveSurface(float _n, const Color& _k) :
ReflectiveSurface(Color(1, 1, 1) * _n, _k), n(_n) {}
As you can see, I forgot to save the (n) value for RefractiveSurface in the constructor.
Small red sphere behind big glass sphere lit from the two sides of the camera:
It looks awesome in motion!D
Thank you for your time, guys. Gotta finish this homework, then I'll rewrite the whole thing and optimize the hell out of it.

Calculate bounce angle aggainst rotated line

I have been trying to implement The second answer of this question
My variables are mainly named the same as in the link.
Here they calculate the bounce angle of a point on a rotated surface with normals,
But I can't seem to do it, am I doing something wrong?
The value output I'm expecting is the new velocity after bouncing on the rotated line, currently my output is doing all crazy kind of things, bouncing to high, bouncing the other way and sometimes the right way but mostly ignoring the rotated angle of my line.
Here's my current Code:
Variables:
Top is the first point of my line
Right is the second point of my line
n is the normal
v is the velocity
dotv is n * v
dotn is n * n
Old Code:
sf::Vector2f n(-(top.y - right.y),(top.x - right.x));
sf::Vector2f dotv = sf::Vector2f(ball.getSpeed().x * n.x, ball.getSpeed().y * n.y);
sf::Vector2f dotn = sf::Vector2f(n.x*n.x,n.y*n.y);
sf::Vector2f u = sf::Vector2f(dotv.x/dotn.x,dotv.y/dotn.y);
u = sf::Vector2f(u.x*n.x,u.y*n.y);
sf::Vector2f w = ball.getSpeed() - u;
ball.setSpeed(sf::Vector2f((sf::Vector2f(w.x*0.5,w.y*0.5)-u)));
Edit:
New Code:
sf::Vector2f n(-(top.y - right.y),(top.x - right.x));
double dotv = ball.getSpeed().x*n.x + ball.getSpeed().y*n.y;
double dotn = n.x*n.x + n.y*n.y;
sf::Vector2f u = sf::Vector2f((dotv/dotn)*n.x, (dotv/dotn)*n.y);
sf::Vector2f w = ball.getSpeed() - u;
ball.setSpeed(sf::Vector2f(ball.getSpeed().x,ball.getSpeed().y) - w);
At first I made the mistake of calculating dotproducts as vectors this has been resolved, now it still gives me a strange output It fires my ball directly trough my object in the angle of the reversed normal
Any help would be greatly appreciated.
One problem I see is that you have dot products as vectors. A dot product results in a scalar (single value).
Also, to make your life a lot easier, you make functions for vector operations and even overload operators when appropriate. E.g. vector addition, subtraction. It's probably best to regular functions for dot product and cross product. Here are some examples of what I mean
class Vector2f
{
// Member of Vector2f
X& operator+=(const Vector2f& other)
{
x += other.x;
y += other.y;
return *this;
}
};
// Not member of Vector2f
inline Vector2f operator+(Vector2f a, const Vector2f& b)
{
a += b;
return a;
}
double dot(const Vector2f& a, const Vector2f& b)
{
return a.getX()*b.getX() + a.getY()*b.getY();
}

How to make manually calculated orbital paths agree with Qt's ellipse drawing method?

I'm attempting to draw celestial bodies moving around on simplified, perfectly circular orbits. I'm also drawing the projected orbital paths these objects will take. However, the problem is that the actual path the objects take doesn't agree with the projection on zooming in closely enough.
Video demonstrating the issue: https://www.youtube.com/watch?v=ALSVfx48zXw
If zoomed out, the problem is non-existent, because the deviation is too small. The apparent size of the deviation appears to be affected primarily by the visible curvature of the circles - notice how the paths of the moons agree with their motion. If one were to zoom in so that the moons' projected paths appear close to straight lines, they would have the same pattern of deviations as the planet shows.
Coordinates calculating methods:
double getX (long int time) {
return orbit * cos(offset + time * speed);
}
double getY (long int time) {
return orbit * sin(offset + time * speed);
}
Projected orbit drawing:
ellipse = scene->addEllipse(system.starX-body.orbit,
system.starY-body.orbit,
body.orbit*2,body.orbit*2,greenPen,transBrush);
Drawing the celestial bodies where they actually appear:
ellipse = scene->addEllipse(-body.radius,
-body.radius,
body.radius*2,body.radius*2,blackPen,greenBrush);
ellipse->setFlag(QGraphicsItem::ItemIgnoresTransformations);
ellipse->setPos(system.starX+body.getX(date2days(game.date)),
system.starY+body.getY(date2days(game.date)));
How do I fix this so that the celestial bodies are always on the predicted curve?
EDIT1:
I have attempted using the suggested algorithm for drawing my own ellipse. The version adapted for use with Qt I reproduce here:
QPoint get_point(double a, double b, double theta, QPoint center)
{
QPoint point;
point.setX(center.x() + a * cos(theta));
point.setY(center.y() + b * sin(theta));
return point;
}
void draw_ellipse(double a, double b, QPoint center, double zoom_factor, QGraphicsScene * scene, QPen pen)
{
double d_theta = 1.0d / zoom_factor;
double theta = 0.0d;
int count = 2.0d * 3.14159265358979323846 / d_theta;
QPoint p1, p2;
p1 = get_point(a, b, 0.0f, center);
for (int i = 0; i <= count; i++)
{
theta += d_theta;
p2 = p1;
p1 = get_point(a, b, theta, center);
scene->addLine(p1.x(),p1.y(),p2.x(),p2.y(),pen);
}
}
The results weren't encouraging:
In addition to not looking pretty at zoom_factor 360, the application ran extremely sluggishly, using much more resources than previously.
EDIT2:
The improved version gives much better results, but still slow. Here is the code:
QPointF get_point(qreal a, qreal b, qreal theta, QPointF center)
{
QPointF point;
point.setX(center.x() + a * cos(theta));
point.setY(center.y() + b * sin(theta));
return point;
}
void draw_ellipse(qreal a, qreal b, QPointF center, qreal zoom_factor, QGraphicsScene * scene, QPen pen)
{
qreal d_theta = 1.0d / zoom_factor;
qreal theta = 0.0d;
int count = 2.0d * 3.14159265358979323846 / d_theta;
QPointF p1, p2;
p1 = get_point(a, b, 0.0f, center);
for (int i = 0; i <= count; i++)
{
theta = i * d_theta;
p2 = p1;
p1 = get_point(a, b, theta, center);
scene->addLine(p1.x(),p1.y(),p2.x(),p2.y(),pen);
}
}
It appears that Qt does not auto-adjust the drawing precision or 'sampling resolution'.
You could try to draw the ellipse yourself, by drawing a loop of lines. Increase the sample resolution of the drawing when you zoom in - i.e. make the sampled points closer to each other.
Take the parametric equation of an ellipse
x = a cos (theta), y = b sin (theta)
where a and b are the semi-major and semi-minor axes of the ellipse, and sample the points with it:
(pseudo C++-style code)
point get_point(float theta, point center)
{
return point(center.x + a * cos(theta), center.y + b * sin(theta));
}
void draw_ellipse(float a, float b, point center, float zoom_factor)
{
float d_theta = 1.0f / zoom_factor;
float theta = 0.0f;
int count = 2.0f * PI / d_theta;
point p1, p2;
p1 = get_point(0.0f, center);
for (int i = 0; i < count; i++)
{
theta += d_theta;
p2 = p1;
p1 = get_point(theta, center);
drawline(p1, p2);
}
}
Sorry if the code looks arbitrary (I'm not familiar with Qt), but you get the point.
Assuming that all of the parameters you pass to addEllipse are of sufficient resolution, the issue seems to be with how Qt renders ellipses. The discretization used in ellipse drawing is not dependent on the transformation matrix of the view.
When a QGraphicsItem is being rendered in a view, its paint method certainly has access to the paint device (in this case: a widget). It could certainly determine the proper discretization step in terms of angle. Even if a graphics item were to render using regular painter calls, the painter has the same information, and the paint device certainly has this information in full. Thus there's no reason for Qt to do what it does, I think. I'll have to trace into this code and see why it fails so badly.
The only fix is for you to implement your own ellipse item, and chose the discretization step and begin/end angles according to the viewport size at the time of rendering.
qreal is a double - so that shouldn't be an issue unless Qt is configured with -qreal float.

Wave vector in 2 dimensions

So I'm trying to make the player shoot a bullet that goes towards the mouse in a wavey pattern. I can get the bullet to move in a wavey pattern (albeit not really how I predicted), but not towards the mouse.
Vector2 BulletFun::sine(Vector2 vec) {
float w = (2 * PI) / 1000; // Where 1000 is the period
float waveNum = (2 * PI) / 5; // Where 5 is the wavelength
Vector2 k(0.0F, waveNum);
float t = k.dot(vec) - (w * _time);
float x = 5 * cos(t); // Where 5 is the amplitude
float y = 5 * sin(t);
Vector2 result(x, y);
return result;
}
Right now the speed isn't much of a concern, that shouldn't be too much of a problem once I have this figured out. I do get some angle change, but it seems to be reversed and only 1/8th a circle.
I'm probably miscalculating something somewhere. I just kind of learned about wave vectors.
I've tried a few other things, such as 1 dimensional travelling waves and another thing involving adjusting a normal sine wave by vec. Which had more or less the same result.
Thanks!
EDIT:
vec is the displacement from the player's location to the mouse click location. The return is a new vector that is adjusted to follow a wave pattern, BulletFun::sine is called each time the bullet receives and update.
The setup is something like this:
void Bullet::update() {
_velocity = BulletFun::sine(_displacement);
_location.add(_velocity); // add is a property of Tuple
// which Vector2 and Point2 inherit
}
In pseudocode, what you need to do is the following:
waveVector = Vector2(travelDistance,amplitude*cos(2*PI*frequency*travelDistance/unitDistance);
cosTheta = directionVector.norm().dot(waveVector.norm());
theta = acos(cosTheta);
waveVector.rotate(theta);
waveVector.translate(originPosition);
That should compute the wave vector in a traditional coordinate frame, and then rotate it to the local coordinate frame of the direction vector (where the direction vector is the local x-axis), and then translate the wave vector relative to your desired origin position of the wave beam or whatever...
This will result in a function very similar to
Vector2
BulletFun::sine(Bullet _bullet, float _amplitude, float _frequency, float _unitDistance)
{
float displacement = _bullet.getDisplacement();
float omega = 2.0f * PI * _frequency * _displacement / _unitDistance;
// Compute the wave coordinate on the traditional, untransformed
// Cartesian coordinate frame.
Vector2 wave(_displacement, _amplitude * cos(omega));
// The dot product of two unit vectors is the cosine of the
// angle between them.
float cosTheta = _bullet.getDirection().normalize().dot(wave.normalize());
float theta = acos(cosTheta);
// Translate and rotate the wave coordinate onto
// the direction vector.
wave.translate(_bullet.origin());
wave.rotate(theta);
}