AudioKit: How to make Knob from AnalogSynthX-Example exponential instead of linear? - ios

For volume controls in most cases it would be better if knob values would change exponential or logarithmical instead of linear.
Where would be the best place within the Knob.swift of the AudioKit AnalogSynthX-Example class to scale the value to any kind of curve?
I think of
func setPercentagesWithTouchPoint(_ touchPoint: CGPoint) {
// Knobs assume up or right is increasing, and down or left is decreasing
let horizontalChange = Double(touchPoint.x - lastX) * knobSensitivity
value += horizontalChange * (maximum - minimum)
let verticalChange = Double(touchPoint.y - lastY) * knobSensitivity
value -= verticalChange * (maximum - minimum)
lastX = touchPoint.x
lastY = touchPoint.y
// TODO: map to exponential/log/any curve if -> knobType is .exp
// ...
delegate?.updateKnobValue(value, tag: self.tag)
}
but maybe someone did invent this wheel already? Thnx!

Thanks for asking. The cutoff knob in the Analog Synth X repo scales logarithmically. You can look at that for a simple example.
Plus, there are new knobs in the AudioKit ROM Player repo. These improved knob controls have adjustable taper curve scaling and range settings:
https://github.com/AudioKit/ROMPlayer

Related

Applying impulse at angle based on touch location

I'm currently developing a game with a cannon that shoots a projectile, I'm having trouble figuring out how to get the projectile to fire at the angle based on the touch location and how far away it is from the cannon. this is the code i'm using below.
let dx = cannon.position.x - (touchLocation.x)
let dy = cannon.position.y - (touchLocation.y)
let angle = atan2(dy, dx)
bullet.zRotation = angle
bulletspeed = Double.random(in: 1...6)
//let angle1 = Double.random(in: 0.2...5); let angle2 = Double.random(in: 1...4)
// dx must be somewhere between 0.2 to 5
bullet.physicsBody?.applyImpulse(CGVector(dx: -angle , dy: -angle))
this doesn't seem to work and i've resorted to using the angle as my x and y values which works but not well.
I'm trying to get the cannon to fire based on the angle of the touch location and to change the speed/power of the projectile by how far way the touch location is from the cannon. How can I do this?
The vector you need to use takes in dx and dy as parameters. You already have these but you say the speed is too fast. That’s because the length of the vector is the speed.
So in your example the speed can be calculated like...
sqrt(dx*dx+dy*dy)
What you need to do is calculate a ‘unit vector’ that is, a vector with length equal to one.
You can do this by dividing dx and dy by the length of the vector.
So...
touchDX = //your calculation
touchDY = //your calculation
touchLength = sqrt(touchDX*touchDX+touchDY*touchDY)
unitVectorDX = touchDX / touchLength
unitVectorDY = touchDY / touchLength
// now put the speed you want in...
speed = 10
vector = CGVector(dx: unitVectorDX * speed, dy: unitVectorDY * speed)
Now, if you use the vector in your impulse it will have the correct direction and speed.
Quick side note, I’m typing on my iPad so don’t have access to code completion etc... you may be able to do this using APIs on CGVector. I think I remember a ‘unitVector’ property that returns a unit vector. But I may be mistaken.

SpriteKit stop spinning wheel in a defined angle

I have a spinning wheel rotating at an angular speed ω, no acceleration involved, implemented with SpriteKit.
When the user push a button I need to slowly decelerate the wheel from the current angle ∂0 and end-up in a specified angle (lets call it ∂f).
I created associated to it a mass of 2.
I already tried the angularDamping and the SKAction.rotate(toAngle: duration:) but they do not fit my needs because:
With the angularDamping I cannot specify easy the angle ∂f where I want to end up.
With the SKAction.rotate(toAngle: duration:) I cannot start slowing down from the current rotation speed and it doesn't behave natural.
The only remaining approach I tried is by using the SKAction.applyTorque(duration:).
This sounds interesting but I have problems calculating the formula to obtain the correct torque to apply and especially for the inertia and radius of the wheel.
Here is my approach:
I'm taking the starting angular velocity ω as:
wheelNode.physicsBody?.angularVelocity.
I'm taking the mass from wheelNode.physicsBody?.mass
The time t is a constant of 10 (this means that in 10 seconds I want the wheel decelerating to the final angle ∂f).
The deceleration that I calculated as:
let a = -1 * ω / t
The inertia should be: let I = 1/2 * mass * pow(r, 2)*. (see notes regarding the radius please)
Then, finally, I calculated the final torque to apply as: let t = I * a (taking care that is opposite of the current angular speed of the wheel).
NOTE:
Since I don't have clear how to have the radius of the wheel I tried to grab it both from:
the wheelNode.physicsBody?.area as let r = sqrt(wheelNode.physicsBody?.area ?? 0 / .pi)
by converting from pixel to meters as the area documentation says. Then I have let r = self.wheelNode.radius / 150.
Funny: I obtain 2 different values :(
UNFORTUNATLY something in this approach is not working because so far I have no idea how to end up in the specified angle and the wheel doesn't stop anyway as it should (or the torque is too much and spins in the other direction, or is not enough). So, also the torque applied seems to be wrong.
Do you know a better way to achieve the result I need? Is that the correct approach? If yes, what's wrong with my calculations?
Kinematics makes my head hurt, but here you go. I made it to where you can input the amount of rotations and the wheel will rotate that many times as its slowing down to the angle you specify. The other function and extension are there to keep the code relatively clean/readable. So if you just want one giant mess function go ahead and modify it.
• Make sure the node's angularDampening = 0.0
• Make sure the node has a circular physicsbody
// Stops a spinning SpriteNode at a specified angle within a certain amount of rotations
//NOTE: Node must have a circular physicsbody
// Damping should be from 0.0 to 1.0
func decelerate(node: SKSpriteNode, toAngle: CGFloat, rotations: Int) {
if node.physicsBody == nil { print("Node doesn't have a physicsbody"); return } //Avoid crash incase node's physicsbody is nil
var cw:CGFloat { if node.physicsBody!.angularVelocity < CGFloat(0.0) { return -1.0} else { return 1.0} } //Clockwise - using int to reduce if statments with booleans
let m = node.physicsBody!.mass // Mass
let r = CGFloat.squareRoot(node.physicsBody!.area / CGFloat.pi)() // Radius
let i = 0.5 * m * r.squared // Intertia
let wi = node.physicsBody!.angularVelocity // Initial Angular Velocity
let wf:CGFloat = 0 // Final Angular Velocity
let ti = CGFloat.unitCircle(node.zRotation) // Initial Theta
var tf = CGFloat.unitCircle(toAngle) // Final Theta
//Correction constant based on rate of rotation since there seems to be a delay between when the action is calcuated and when it is run
//Without the correction the node stops a little off from its desired stop angle
tf -= 0.00773889 * wi //Might need to change constn
let dt = deltaTheta(ti, tf, Int(cw), rotations)
let a = -cw * 0.5 * wi.squared / abs(dt) // Angular Acceleration - cw used to determine direction
print("A:\(a)")
let time:Double = Double(abs((wf-wi) / a)) // Time needed to stop
let torque:CGFloat = i * a // Torque needed to stop
node.run(SKAction.applyTorque(torque, duration: time))
}
func deltaTheta(_ ti:CGFloat, _ tf:CGFloat, _ clockwise: Int, _ rotations: Int) -> CGFloat {
let extra = CGFloat(rotations)*2*CGFloat.pi
if clockwise == -1 {
if tf>ti { return tf-ti-2*CGFloat.pi-extra }else{ return tf-ti-extra }
}else{
if tf>ti { return tf-ti+extra }else{ return tf+2*CGFloat.pi+extra-ti }
}
}
}
extension CGFloat {
public var squared:CGFloat { return self * self }
public static func unitCircle(_ value: CGFloat) -> CGFloat {
if value < 0 { return 2 * CGFloat.pi + value }
else{ return value }
}
}

Calculate correct impluse or force to move a Box2D body to a specific position - Box2D

i have a question about moving a Box2D body to a specific position without using this for example.
body->SetTransform(targetVector,body->GetAngle())
I have some code which works for applyForce (here):
const float destinationControl = 0.3f;
b2Vec2 missilePosition = _physicalBody->GetPosition();
b2Vec2 diff = targetPosition - missilePosition;
float dist = diff.Length();
if (dist > 0)
{
// compute the aiming direction
b2Vec2 direction = b2Vec2(diff.x / dist, diff.y / dist);
// get the current missile velocity because we will apply a force to compensate this.
b2Vec2 currentVelocity = _physicalBody->GetLinearVelocity();
// the missile ideal velocity is the direction to the target multiplied by the max speed
b2Vec2 desireVelocity = b2Vec2(direction.x * maxSpeed, direction.y * maxSpeed);
// compensate the current missile velocity by the desired velocity, based on the control factor
b2Vec2 finalVelocity = control * (desireVelocity - currentVelocity);
// transform our velocity into an impulse (get rid of the time and mass factor)
float temp = (_physicalBody->GetMass() / normalDelta);
b2Vec2 finalForce = b2Vec2(finalVelocity.x * temp, finalVelocity.y * temp);
_physicalBody->ApplyForce(finalForce, _physicalBody->GetWorldCenter());
}
But the when the maxSpeed is to high the body move over the point to fast.
So does anyone know how to calculate a force (ApplyForce) or an impluse (ApplyLinearImpulse) to move the body to a target position (very exactly) in a specific time.
Or a solution with the code above. I mean calculate the maxSpeed to move the body in a specific time to the target position.
In my google search i found the interesting article from iforce about projected trajectory
(here). Maybe this could be help too?
Thank you in advance
I think you have it mostly correct, but you are not checking to see if the body will overshoot the target in the next time step. Here is what works for me:
b2Vec2 targetPosition = ...;
float targetSpeed = ...;
b2Vec2 direction = targetPosition - body->GetPosition();
float distanceToTravel = direction.Normalize();
// For most of the movement, the target speed is ok
float speedToUse = targetSpeed;
// Check if this speed will cause overshoot in the next time step.
// If so, we need to scale the speed down to just enough to reach
// the target point. (Assuming here a step length based on 60 fps)
float distancePerTimestep = speedToUse / 60.0f;
if ( distancePerTimestep > distanceToTravel )
speedToUse *= ( distanceToTravel / distancePerTimestep );
// The rest is pretty much what you had already:
b2Vec2 desiredVelocity = speedToUse * direction;
b2Vec2 changeInVelocity = desiredVelocity - body->GetLinearVelocity();
b2Vec2 force = body->GetMass() * 60.0f * changeInVelocity;
body->ApplyForce( force, body->GetWorldCenter(), true );
There is a way for single-time applied force to move by given distance (previous answer suggests that you can correct error in calculation by additional force in future frames):
public static void applyForceToMoveBy(float byX, float byY, Body body) {
force.set(byX, byY);
force.sub(body.getLinearVelocity());
float mass = body.getMass();
force.scl(mass * 30.45f);
body.applyForceToCenter(force, true);
}
Known limitations:
1) LinearVelocity effect was not tested;
2) calculation was tested with body linear damping = 0.5f. Appreciate, if somebody know how to add it into formula;
3) magic number 30.45f - maybe this could be fixed by point 2 or by world frame delta.

Animating rotation changes of UIImageView

I'm making an app that (among other things) displays a simplified compass image that rotates according to the device's rotation. The problem is that simply doing this:
float heading = -1.0f * M_PI * trueHeading / 180.0f; //trueHeading is always between 0 and 359, never 360
self.compassNeedle.transform = CGAffineTransformMakeRotation(heading);
inside CLLocationManager's didUpdateHeading method makes the animation ugly and choppy.
I have already used Instruments to find out whether its simply my app not being able to render at more than 30-48 fps, but that's not the case.
How can I smooth out the image view's rotation so that it's more like Apple's own Compass app?
Instead of using the current instant value, try using the average of the last N values for the true heading. The value may be jumping around a lot in a single instant but settle down "in the average".
Assuming you have a member variable storedReadings which is an NSMutableArray:
-(void)addReading(float):newReading
{
[storedReadings addObject:[NSNumber numberWithFloat:newReading]];
while([storedReadings count] > MAX_READINGS)
{
[storedReadings removeObjectAtIndex:0];
}
}
then when you need the average value (timer update?)
-(float)calcReading
{
float result = 0.0f;
if([storedReadings count] > 0)
{
foreach(NSNumber* reading in storedReadings)
{
result += [reading floatValue];
}
result /= [storedReadings count];
}
return result;
}
You get to pick MAX_READINGS a priori.
NEXT LEVEL(S) UP
If the readings are not jumping around so much but the animation is still choppy, you probably need to do something like a "smooth" rotation. At any given time, you have the current angle you are displaying, theta (store this in your class, start it out at 0). You also have your target angle, call it target. This is the value you get from the smoothed calcReading function. The error is defined as the difference between the two:
error = target-theta;
Set up a timer callback with a period of something like 0.05 seconds (20x per second). What you want to do is adjust theta so that the error is driven towards 0. You can do this in a couple of ways:
thetaNext += kProp * (target - theta); //This is proportional feedback.
thetaNext += kStep * sign(target-theta); // This moves theta a fixed amount each update. sign(x) = +1 if x >= 0 and -1 if x < 0.
The first solution will cause the rotation to change sharply the further it is from the target. It will also probably oscillate a little bit as it swings past the "zero" point. Bigger values of kProp will yield faster response but also more oscillation. Some tuning will be required.
The second solution will be much easier to control...it just "ticks" the compass needle around each time. You can set kStep to something like 1/4 degree, which gives you a "speed" of rotation of about (1/4 deg/update) * (20 updates/seconds) = 5 degrees per second. This is a bit slow, but you can see the math and change kStep to suit your needs. Note that you may to "band" the "error" value so that no action is taken if the error < kStep (or something like that). This prevents your compass from shifting when the angle is really close to the target. You can change kStep when the error is small so that it "slides" into the ending position (i.e. kStep is smaller when the error is small).
For dealing with Angle Issues (wrap around), I "normalize" the angle so it is always within -Pi/Pi. I don't guarantee this is the perfect way to do it, but it seems to get the job done:
// Takes an angle greater than +/- M_PI and converts it back
// to +/- M_PI. Useful in Box2D where angles continuously
// increase/decrease.
static inline float32 AdjustAngle(float32 angleRads)
{
if(angleRads > M_PI)
{
while(angleRads > M_PI)
{
angleRads -= 2*M_PI;
}
}
else if(angleRads < -M_PI)
{
while(angleRads < -M_PI)
{
angleRads += 2*M_PI;
}
}
return angleRads;
}
By doing it this way, -pi is the angle you reach from going in either direction as you continue to rotate left/right. That is to say, there is not a discontinuity in the number going from say 0 to 359 degrees.
SO PUTTING THIS ALL TOGETHER
static inline float Sign(float value)
{
if(value >= 0)
return 1.0f;
return -1.0f;
}
//#define ROTATION_OPTION_1
//#define ROTATION_OPTION_2
#define ROTATION_OPTION_3
-(void)updateArrow
{
// Calculate the angle to the player
CGPoint toPlayer = ccpSub(self.player.position,self.arrow.position);
// Calculate the angle of this...Note there are some inversions
// and the actual image is rotated 90 degrees so I had to offset it
// a bit.
float angleToPlayerRads = -atan2f(toPlayer.y, toPlayer.x);
angleToPlayerRads = AdjustAngle(angleToPlayerRads);
// This is the angle we "wish" the arrow would be pointing.
float targetAngle = CC_RADIANS_TO_DEGREES(angleToPlayerRads)+90;
float errorAngle = targetAngle-self.arrow.rotation;
CCLOG(#"Error Angle = %f",errorAngle);
#ifdef ROTATION_OPTION_1
// In this option, we just set the angle of the rotated sprite directly.
self.arrow.rotation = CC_RADIANS_TO_DEGREES(angleToPlayerRads)+90;
#endif
#ifdef ROTATION_OPTION_2
// In this option, we apply proportional feedback to the angle
// difference.
const float kProp = 0.05f;
self.arrow.rotation += kProp * (errorAngle);
#endif
#ifdef ROTATION_OPTION_3
// The step to take each update in degrees.
const float kStep = 4.0f;
// NOTE: Without the "if(fabs(...)) check, the angle
// can "dither" around the zero point when it is very close.
if(fabs(errorAngle) > kStep)
{
self.arrow.rotation += Sign(errorAngle)*kStep;
}
#endif
}
I put this code into a demo program I had written for Cocos2d. It shows a character (big box) being chased by some monsters (smaller boxes) and has an arrow in the center that always points towards the character. The updateArrow call is made on a timer tick (the update(dt) function) regularly. The player's position on the screen is set by the user tapping on the screen and the angle is based on the vector from the arrow to the player. In the function, I show all three options for setting the angle of the arrow:
Option 1
Just set it based on where the player is (i.e. just set it).
Option 2
Use proportional feedback to adjust the arrow's angle each time step.
Option 3
Step the angle of the arrow each timestep a little bit if the error angle is more than the step size.
Here is a picture showing roughly what it looks like:
And, all the code is available here on github. Just look in the HelloWorldLayer.m file.
Was this helpful?

XNA - controlling an object with keyboard input

Ok so I have a ship which moves up and down based on the axis regardless of where the ship is facing.
How do I make the ship move in the direction it's facing? i.e. if my ship is facing east, key up makes it go north rather than east.
Your question isn't very clear - I will assume you're using models and matrices (as opposed to SpriteBatch or something else). So, making a guess - I'd say that the order of your matrix operations is incorrect.
This answer to a similar question may help.
Each matrix operation happens around the origin. So if you're doing your rotation after you move your ship into position, your rotation will also effectively "rotate" the direction of movement.
The easiest way is to make an angle and velocity variable so when you click left and right you change the angle and when you click up and down you changle the speed of your ship.
KeyboardState ks;
float speed = 0;
float angle = 0;
protected override void Update(GameTime gameTime)
{
ks = Keyboard.GetState();
if(ks.IsKeyDown(Keys.Up)) speed += 10;
if (ks.IsKeyDown(Keys.Down)) speed -= 10;
if (ks.IsKeyDown(Keys.Right)) angle += 10;
if (ks.IsKeyDown(Keys.Left)) angle -= 10;
}
You need to have direction vector like this
Vector3 direction = Vector3.Transform(Vector3.Forward, Matrix.CreateFromYawPitchRoll(yaw, pitch, roll));
Next, get your velocity vector
Vector3 velocity = direction * speed;
And move your ship
float time (float) = gameTime.ElapsedTime.TotalSeconds;
position += velocity * time;
In this example yaw is angle, pitch and roll keep 0.

Resources