Mouse movement angle in openFrameworks - mouse

I am currently in the process of creating a sort of drawing program in openFrameworks that needs to calculate the angle of mouse movement. The reason for this is that the program needs to be able to draw brush strokes similar to the way photoshop does it.
I've been able to get it to work in a very jaggy way. I've placed my code in the MouseDragged event in openFrameworks, but the calculated angle is extremely jaggy and not smooth in anyway. It needs to be smooth in order for the drawing part to look good.
void testApp::mouseMoved(int x, int y ){
dxX = x - oldX;
dxY = y - oldY;
movementAngle = (atan2(dxY, dxX) * 180.0 / PI);
double movementAngleRad;
movementAngleRad = movementAngle * TO_RADIANS;
if (movementAngle < 0) {
movementAngle += 360;
}
testString = "X: " + ofToString(dxX) + " ,";
testString += "Y: " + ofToString(dxY) + " ,";
testString += "movementAngle: " + ofToString(movementAngle);
oldX = x;
oldY = y;
}
I've tried different ways of optimizing the code to work smooth but alas without results.
If you sit with a brilliant idea on how this could be fixed or optimized, I will be very grateful.

I solved it to some degree by using an ofPolyline object.
The following code shows how it works.
void testApp::mouseMoved(int x, int y ){
float angleRad;
if (movement.size() > 4)
{ angleRad = atan2(movement[movement.size()-4].y - y, movement[movement.size()-4].x -x);}
movementAngle = (angleRad * 180 / PI) + 180;
movement.addVertex(x,y,0);
}
As seen in the code I'm using the point recorded 4 steps back to increase the smoothness of the angle. This works if the mouse is moved in stroke like movements. If the mouse is moved slow, jaggyness will still occur.

Related

Rotate PositionComponent around a fixed position(x,y) coordinate

I'm trying to get a PositionComponent to rotate around a central fixed point in the game world, the anchors are all within the component itself so I'm a bit stumped.
Edit: Just for anyone else looking to do something similar managed to get it to work with
void update(double dt){
super.update(dt);
double oldRadian = anchorComponent.angle;
anchorComponent.angle += rotation * dt;
anchorComponent.angle %= 2 * math.pi;
double newRadian = anchorComponent.angle - oldRadian;
rotatingComponent.angle = anchorComponent.angle;
double x = rotatingComponent.position.x;
double y = rotatingComponent.position.y;
rotatingComponent.position.x = cos(newRadian) * (x - anchorComponent.position.x) -
sin(newRadian) * (y - anchorComponent.position.y) +
anchorComponent.position.x;
rotatingComponent.position.y = sin(newRadian) * (x - anchorComponent.position.x) +
cos(newRadian) * (y - anchorComponent.position.y) +
anchorComponent.position.y;
}
Now rotatingComponent rotates around anchorComponent (both positionComponents) when variable rotation changes.
You can use a MoveAlongPathEffect to make the component move in a circle around a point and then you can combine that with the lookAt method to make the component rotate "inwards" so that it looks like it is rotating around the point. You might have to set nativeAngle too, depending on how the PositionComponent that you want to rotate looks like.

SetPixel faster on mouse drag

Hi I'm creating a cleaning game but encountered a problem when I fast draw a straight line the line is broken but when I slow draw a straight line it works fine
Below is my code
private void Update()
{
if (Input.GetMouseButton(0))
{
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out RaycastHit hit))
{
Vector2 textureCoord = hit.textureCoord;
int pixelX = (int)(textureCoord.x * _templateDirtMask.width);
int pixelY = (int)(textureCoord.y * _templateDirtMask.height);
Vector2Int paintPixelPosition = new Vector2Int(pixelX, pixelY);
int paintPixelDistance = Mathf.Abs(paintPixelPosition.x - lastPaintPixelPosition.x) + Mathf.Abs(paintPixelPosition.y - lastPaintPixelPosition.y);
int maxPaintDistance = 7;
if (paintPixelDistance < maxPaintDistance)
{
return;
}
lastPaintPixelPosition = paintPixelPosition;
int pixelXOffset = pixelX - (_brush.width / 2);
int pixelYOffset = pixelY - (_brush.height / 2);
for (int x = 0; x < _brush.width; x++)
{
for (int y = 0; y < _brush.height; y++) {
Color pixelDirt = _brush.GetPixel(x, y);
Color pixelDirtMask = _templateDirtMask.GetPixel(pixelXOffset + x, pixelYOffset + y);
float removedAmount = pixelDirtMask.g - (pixelDirtMask.g * pixelDirt.g);
dirtAmount -= removedAmount;
_templateDirtMask.SetPixel(
pixelXOffset + x,
pixelYOffset + y,
new Color(0, pixelDirtMask.g * pixelDirt.g, 0)
);
}
}
_templateDirtMask.Apply();
}
}
}
Start Paint, and using the pen, try draw circles as fast as you can then look at the result:
Obviously, you didn't draw such straight lines with such clean direction change.
So, how is Paint able to cope up with such huge delta changes?
Interpolation
Some pseudo code:
on mouse down
get current mouse position
if last mouse position has been set
draw all the positions between last to current
use Bresenham algorithm for instance
save current mouse position to last mouse position
You could/should make your algo aware about pen size, with some simple math you can figure out the necessary step in evaluating points in the interpolation.
And don't use SetPixel, keep a copy of the texture pixels with GetPixels32 that you'll update and then upload it all at once using SetPixels32.

Unity3D BezierCurve - Spline Walker Following AI?

I've been struggling to create a game with a competent (but fair) racing AI, and I have several constraints that I'm trying to meet. Here's the conditions in order:
1.) The AI logic and player controls BOTH share the same car controller to drive and turn, etc. The AI vehicle simply passes a clamped (-1 to 1) value depending on how far the car is trying to turn and the throttle is engaged. Both the AI and player share the boolean to brake, and drift turning with the SHIFT key
2.) The AI needs to make smart, informed decisions that the player would in applying the right amount of turn, when to coast, etc.
I originally used a plain waypoint increment system to have the AI continue lapping around the track depending on the waypoints. With the right wheel friction curve values (which I happened to luckily find online) this actually works OK. However, while I was struggling more with the wheel friction values especially, and still want to have a smoother path following and turning logic for the AI, it was suggested to me to use cubic Bezier splines. I found the Catlike Coding tutorial fascinating (I'm sure many of you know this, but here's the link below for anyone interested):
https://catlikecoding.com/unity/tutorials/curves-and-splines/
I then got the idea of using the Spline Walker from this tutorial to be the ONE waypoint for the AI, and effectively "tease" the car to follow the spline walker, like this video:
https://www.youtube.com/watch?v=UcA4K2rmX-U#action=share
However, here's my big problem - if I want to have my car FOLLOW the spline walker, while keeping the spline walker always in front, I have to ensure the "progress" that the spline walker follows is relative to the position of the following car, with the spline walker remaining a LITTLE in front so that the car doesn't decide to slow down and stop.
I've been looking for examples to do this, and I can't say I've been too successful.
Here's my current progress calculating code snippets - I'm trying to store distances between positions on the spline right now, via the old waypoint objects which happen to share the same transform coordinates:
private void Start()
{
Rigidbody rb = chasingCar.GetComponent<Rigidbody>();
if(path)
{
nodes = path.GetComponentsInChildren<Transform>();
}
Array.Resize(ref distances, nodes.Length-1);
for (int i = 0; i < nodes.Length-1; i++)
{
//start storing the distances between two successive waypoints on the spline
distances[i] = Vector3.Distance(nodes[i].position, nodes[i + 1].position);
totalDistance += distances[i];
}
Debug.Log("First distance value is " + distances[0] + " and overall distance est is " + totalDistance);
Debug.Log("Second distance value is " + distances[1] + " and overall distance est is " + totalDistance);
Debug.Log("Fifth distance value is " + distances[4] + " and overall distance est is " + totalDistance);
}
This is in the update function for the spline walker when the chasing car and it's old waypoint path have been provided to the spline:
Vector3 position;
if (chasingCar && path)
{
float distFromCar = Vector3.Distance(transform.position, chasingCar.transform.position);
Debug.Log("Distance from car " + distFromCar);
if(distFromCar < 35)
{
//get current spline waypoint
//int splineIdx = GetSplineIndex(progress);
int splineIdx = chasingCar.GetComponent<CarEngine>().GetCurrentNodeTarget();
//declare next spline waypoint
int splineIdxNext = splineIdx + 1;
if (path && splineIdxNext == (nodes.Length))
splineIdxNext = 0;
Debug.Log("Current splineIdx " + splineIdx);
//float currCarDistance = Vector3.Distance(chasingCar.transform.position, nodes[splineIdx].position);
float currCarDistance = SumSplineProgress(splineIdx);
float overallDistance = Vector3.Distance(nodes[splineIdx].position, nodes[splineIdxNext].position);
float currCarSplineProgress = currCarDistance / overallDistance;
float overallProgress = (currCarDistance) / (totalDistance);
progress = overallProgress;
}
else
{
progress += Time.deltaTime / duration;
}
Debug.Log("Chasing, current progress: " + progress);
position = spline.GetPoint(progress);
Finally, here's the functions I've tried to use to calculate the spline walker progress in the past:
int GetSplineIndex(float progress)
{
float curProgress = progress * (totalDistance);
Debug.Log("Current calculated progress " + curProgress);
return System.Convert.ToInt32(Mathf.Floor(curProgress));
}
float SumSplineProgress(int index)
{
float currTotalDistance = 0f;
for(int i = index; i > -1; i--)
{
currTotalDistance += distances[i];
}
return currTotalDistance;
}
I might just be making it harder on myself than I need to, but I'm just going to say, I'm legit stumped. I got close with having the spline waypoint jump ahead of the car MORE when there is more distance between the current start and end waypoint for the AI car, but that's still not what I'm trying to achieve.
Anyone have any particular suggestions here? Tips, nudges in the direction, and code would be fantastic. Thanks in advance!
UPDATE
Yes, I'm still working on this! There was some logic that I regarded as faulty in the previous spline calculation code - for instance, this:
float currCarSplineProgress = currCarDistance / overallDistance;
I've changed to this:
float currCarSplineProgress = (currCarDistance) / currSplineLength;
The idea of that part is to check the car's progress on the current curve it is traveling close to in the overall spline, and position the spline walker accordingly so that it jumps ahead to the next spline when needed. Here's the full updated code:
Vector3 position;
if (chasingCar && path)
{
float distFromCar = Vector3.Distance(transform.position, chasingCar.transform.position);
Debug.Log("Distance from car " + distFromCar);
if(distFromCar < 50)
{
//get current spline waypoint
//int splineIdx = GetSplineIndex(progress);
int splineIdx = chasingCar.GetComponent<CarEngine>().GetCurrentNodeTarget()-1;
//declare next spline waypoint
int splineIdxNext = splineIdx + 1;
if(splineIdx == -1)
{
splineIdx = nodes.Length - 2;
splineIdxNext = 0;
}
if (path && splineIdxNext == (nodes.Length))
splineIdxNext = 0;
Debug.Log("Current splineIdx " + splineIdx);
//float currCarDistance = GetConvertedDistance(chasingCar.transform.position, nodes[splineIdx].position);
float currCarDistance = Vector3.Distance(chasingCar.transform.position, nodes[splineIdx].position);
float restDistance = Vector3.Distance(chasingCar.transform.position, nodes[splineIdxNext].position);
//float currCarDistance = SumSplineProgress(splineIdx);
Debug.Log("currCarDistance " + currCarDistance);
//float currSplineLength = Vector3.Distance(nodes[splineIdx].position, nodes[splineIdxNext].position);
float currSplineLength = currCarDistance + restDistance;
float overallDistance = 0;
float nextOverallDist = 0f;
if(splineIdx != 0)
overallDistance = SumSplineProgress(splineIdx-1);
Debug.Log("overallDistance " + overallDistance);
float currCarSplineProgNext = 0f;
if (splineIdxNext != 1 && splineIdxNext != 0)
{
nextOverallDist = SumSplineProgress(splineIdxNext - 1);
currCarSplineProgNext = (currCarDistance) / nextOverallDist;
}
Debug.Log("currSplineLength " + currSplineLength);
float currCarSplineProgress = (currCarDistance) / currSplineLength;
float leading = 10f;
if (distFromCar < 20)
leading += 15f;
float overallProgress;
Debug.Log("currCarSplineProgress " + currCarSplineProgress);
if (currCarSplineProgress < .7f)
{
overallProgress = (currSplineLength + (currCarDistance * .3f)) / (totalDistance);
}
else
{
Debug.Log("Jumping to next waypoint...");
overallProgress = (nextOverallDist + (currCarDistance * .3f)) / (totalDistance);
}
Debug.Log("Overall progress " + overallProgress);
//if (overallProgress >= 1f)
// overallProgress = 0f;
progress = overallProgress;
}
else
{
progress += Time.deltaTime / duration;
}
Debug.Log("Chasing, current progress: " + progress);
position = spline.GetPoint(progress);
}
else
{
position = spline.GetPoint(progress);
}
transform.localPosition = position;
Yet, unexpected things STILL happen when the car makes enough progress - the spline walker will just suddenly jump to one of the previous sections!
Any insights?
You have the right idea for making the AI chase a target moving along the spline. I believe that's how most AI in racing games work.
To ensure the target is always ahead of the AI, set the target's position to the AI's position on the spline added by some value related to how fast the AI is moving.
I would suggest checking out the Unity Standard Assets package:
https://assetstore.unity.com/packages/essentials/asset-packs/standard-assets-for-unity-2017-3-32351
There is a car AI system in there that works by following a target that is moving along a spline.

Projectile Motion in Cocos2d iphone

I want to throw a ball that has a projectile motion. I have a monkey on centre of screen and onTouchBegin I am taking the starting point of the touch and onTouchEnded I am taking the ending points. From the starting and ending points I am taking the angle value between them. Like 30 degrees, 45 or 90 degree.
This is my code by which I have calculated angle of start to endpoint
float angleRadians = atan2(startTouchPoint.x - touchPoint.x, startTouchPoint.y - touchPoint.y);
float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians);
float cocosAngle = -1 * angleDegrees;
Now i am using Projectile motion formula to throw ball with angle i have calculated from above formula .
inside init method
gravity = 9.8; // metres per second square
X = 0;
Y = 0;
V0 = 50; // meters per second -- elevation
VX0 = V0 * cos(angle); // meters per second
VY0 = V0 * sin(angle); // meters per second
gameTime = 0;
and onTouchEnded i have called fire method which will throw ball .
-(void)fire:(ccTime) dt
{
CCLOG(#"Angle 1: %.2f",angle);
gameTime += dt*6;
// x = v0 * t * cos(angle)
X = (V0 * gameTime * cos(angle))/2+120;
// y = v0 * t * sin(angle) - 0.5 * g * t^2
Y = (V0 * gameTime * sin(angle) - 0.5 * gravity * pow(gameTime, 2))/2+255;
if (Y > 50)
{
sprite_webfire.position = ccp(X,Y);
flag = true;
}
else
{
//angleValue += 15;
angleValue = angle;
angle = [self DegreesToRadians:angleValue];
gravity = 9.8; // metres per second square
X = 0;
Y = 0;
V0 = 50; // meters per second -- elevation
VX0 = V0 * cos(angle); // meters per second
VY0 = V0 * sin(angle); // meters per second
gameTime = 0;
// [self pauseSchedulerAndActions];
}
if (Y < 50)
{
[self unschedule:#selector(fire:)];
}
NSLog(#"ball (%lf,%lf), dt = %lf angle value %d", X, Y, dt,angleValue);
}
this code is working . by this code i can throw ball in projectile motion but i cant throw it where i want to. i cant throw wrt to given angle from start to end point.
i can throw it like red mark but i want to throw it blue mark with swipe . but its not throwing like i am swiping screen.
I am not certain on what math you are using to do this, I find your documentation a bit confusing.
Generally, for project tile motion this is what you need to do:
Find out what the take off angle is relative to the horizontal. Then depending on whatever initial velocity you want the object to have, use that and you trig equations to put your initial velocities into rectangular components.
For example:
If initial velocity was 10, the initial velocity in the y direction would be 10sin(angle), and in the x direction it would be 10cos(angle).
Then in to update the position of the sprite you should use kinematics equations: http://www.physicsclassroom.com/class/1dkin/u1l6c.cfm
First update velocities:
Velocity in the Y direction: V = v(initial) + gravity*(Delta-time)
Velocity in the X direction is constant unless you want to factor in some sort of resistance to make things a lot more complicated.
then position y = oldPositionY + velocity(in Y direction)*(Delta-time) + 1/2(gravity)(delta-time)^2.
and position x = oldPositionX + Xvelocity*delta-time
I have done some projectile motion stuff, and I have found you need to make gravity a large constant, something around 500 to make it look life-like. Let me know if this is confusing or you don't know how to implement it.
I would suggest that you take a look at the following tutorial: http://www.raywenderlich.com/4756/how-to-make-a-catapult-shooting-game-with-cocos2d-and-box2d-part-1.
It shows you how to use a physics engine, so you don't need to do much of the math. All the 'bullets' in the tutorial are also moving with projectile motion.
I'll add a bit to what was already said (which was good). Firstly, you should not be wasting time computing any angles. Stick with vectors for your velocity. In other words, get the initial velocity vector from the touch start and end location, and that will be your (v0x, v0y). For example:
CGPoint initialVelocity = ccpSub(touchPoint, startTouchPoint);
float v0x = initialVelocity.x;
float v0y = initialVelocity.y;
If you wish to assign a different magnitude to the initial velocity vector, simply normalize it and then multiply it by a new magnitude.
CGPoint unitVelocity = ccpNormalize(initialVelocity);
float magnitude = 200; // or whatever you want it to be
CGPoint velocity = ccpMult(unitVelocity, magnitude);
Anyway, with this velocity set properly you can then use it in your position calculations as before, but without the added complexity of calculating the angles.
-(void) fire:(ccTime)dt
{
.
.
gameTime += dt;
// if x(t) = x0 + v0x*t, then dx = v0x*dt
x += v0x*dt;
// if y(t) = y0 + v0y*t - 0.5t^2, then dy = v0y*dt - g*t*dt
y += (v0y * dt - g*gameTime*dt);
.
.
}
Also you should not set v0 = 50. Calculate the velocity from the vector as I suggested.
Something important to consider is that you are calculating what the movement should be in a physical world based upon units of meters. The screen is operating in points, not meters, so you will probably have to apply a scaling factor to the new position (x,y) to get the look that you are going for.
Edit: my bad, I had to revisit my math in the position calculation. My differentials was a bit rusty.

Sprite has a jigging effect because of tracking

I have a sprite that tracks and follows objects on the screen, moving towards them.
The method runs on a schedule and basically looks like this:
- (void) nextFrame:(ccTime)dt {
//calculate distance between the bubble and the fish
float dx = bubbleToChase.position.x - fish.position.x;
float dy = bubbleToChase.position.y - fish.position.y;
float d = sqrt(dx*dx + dy*dy);
float v = 400;
if (d > 190){
NSLog(#"moving the fish!");
fish.position = ccp( fish.position.x + dx/d * v *dt,
fish.position.y + dy/d * v *dt);
}
}
The code works pretty well, when the distance is greater than 190 the fish will swim towards it.
The issue is that the objects have physics, so they are sliding around the screen. This produces a jigging / staggering effect on the fish sprite, because the fish will stop once it reaches the bubble, but then jiggle and stop rapidly as the bubble drifts away as (d > 190) incrementally.
How can I get rid of this jigging effect? I'd like to just stop the fish from moving once it has reached the bubble's position. Or any alternative that smooths it out. Any help appreciated, thanks.
if (d > 190 && !fish.parked){
NSLog(#"moving the fish!");
fish.position = ccp( fish.position.x + dx/d * v *dt,
fish.position.y + dy/d * v *dt);
}else{
if( fish.parked ){
// what you want to do while parked
// just sit there, wander randomly,
// then unpark the fish...
if(unpark)
fish.parked=FALSE;
}else{
fish.parked=TRUE;
// set variables for parked state.
}
}