i have several circles drawn programmatically on the screen . I then work out the distance between the finger click’s x and y coordinates with each of the circle’s x and y coordinates.
Which ever distance is less than any of the circle’s radius is the circle that was clicked on. Quite simple really. However im finding that ive got a lot of repeated code and i feel that i can clean up the code but im not sure what the best way to do it at the moment.
any help is appreciated.
float diffx = touch.x - bass.pos.x;
float diffy = touch.y - bass.pos.y;
float dist = sqrt(diffx*diffx + diffy*diffy);
if(dist < bass.radius){
if(recordingInfo.isRecording){
//do some stuff related to this button unique
}
//play some sound
}
diffx = touch.x - treble.pos.x;
diffy = touch.y - treble.pos.y;
dist = sqrt(diffx*diffx + diffy*diffy);
if(dist < treble.radius){
if(recordingInfo.isRecording){
//do something related to this button
}
//play some sound
}
diffx = touch.x - hihat.pos.x;
diffy = touch.y - hihat.pos.y;
dist = sqrt(diffx*diffx + diffy*diffy);
if(dist < hihat.radius){
if(recordingInfo.isRecording){
//do shayt related to this button
}
//play this sound
}
diffx = touch.x - bassTwo.pos.x;
diffy = touch.y - bassTwo.pos.y;
dist = sqrt(diffx*diffx + diffy*diffy);
if(dist < bassTwo.radius){
if(recordingInfo.isRecording){
//do some crap regarding this indivudal button
}
//play another sound
}
diffx = touch.x - kick.pos.x;
diffy = touch.y - kick.pos.y;
dist = sqrt(diffx*diffx + diffy*diffy);
if(dist < kick.radius){
if(recordingInfo.isRecording){
//do some funky stuff related to this button
}
//play some sound
}
diffx = touch.x - snare.pos.x;
diffy = touch.y - snare.pos.y;
dist = sqrt(diffx*diffx + diffy*diffy);
if(dist < snare.radius){
if(recordingInfo.isRecording){
//
}
//play some sound
}
diffx = touch.x - recordButton.pos.x;
diffy = touch.y - recordButton.pos.y;
dist = sqrt(diffx*diffx + diffy*diffy);
if(dist < recordButton.radius){
//and do some funky stuff audio visual styff gere
}
diffx = touch.x - play.pos.x;
diffy = touch.y - play.pos.y;
dist = sqrt(diffx*diffx + diffy*diffy);
//code execution if this circle button is hit
}
or is this fine? i place all of this code in the touchDown method
The repeated code is:
Any time code appears more than once you should consider putting it in a function:
Of course, you’re also repeating that check to see if a button has been hit:
This is a very simple method of handling events and it’s hard to reduce the repetition further without changing the program’s architecture. If you want something a little more flexible you might want to look into how GUI frameworks handle events. The Cocoa documentation on the events might be a good example to look at: Cocoa Event-Handling Guide