I have a stage with a movie clip with the instance name of "mc". Currently I have a code that is suppose to move the player left and right, and when the left or right key is released, the "mc" slides a little bit. The problem I'm having is that making the "mc" move to the left works, but the exact some code used for the right doesn't.
All of this code is present on the Main Stage - Frame One
//Variables
var mcSpeed:Number = 0;//MC's Current Speed
var mcJumping:Boolean = false;//if mc is Jumping
var mcFalling:Boolean = false;//if mc is Falling
var mcMoving:Boolean = false;//if mc is Moving
var mcSliding:Boolean = false;//if mc is sliding
var mcSlide:Number = 0;//Stored for use when creating slide
var mcMaxSlide:Number = 1.6;//Max Distance the object will slide.
//Player Move Function
p1Move = new Object();
p1Move = function (dir:String, maxSpeed:Number) {
if (dir == "left" && _root.mcSpeed<maxSpeed) {
_root.mcSpeed += .2;
_root.mc._x -= _root.mcSpeed;
} else if (dir == "right" && _root.mcSpeed<maxSpeed) {
_root.mcSpeed += .2;
_root.mc._x += _root.mcSpeed;
} else if (dir == "left" && speed>=maxSpeed) {
_root.mc._x -= _root.mcSpeed;
} else if (dir == "right" && _root.mcSpeed>=maxSpeed) {
_root.mc._x += _root.mcSpeed;
}
}
//onEnterFrame for MC
mc.onEnterFrame = function():Void {
if (Key.isDown(Key.LEFT)) {
if (_root.mcMoving == false && _root.mcSliding == false) {
_root.mcMoving = true;
} else if (_root.mcMoving == true && _root.mcSliding == false) {
_root.p1Move("left",5);
}
} else if (!Key.isDown(Key.LEFT)) {
if (_root.mcMoving == true && _root.mcSliding == false) {
_root.mcSliding = true;
} else if (_root.mcMoving == true && _root.mcSliding == true && _root.mcSlide<_root.mcMaxSlide) {
_root.mcSlide += .2;
this._x -= .2;
} else if (_root.mcMoving == true && _root.mcSliding == true && _root.mcSlide>=_root.mcMaxSlide) {
_root.mcMoving = false;
_root.mcSliding = false;
_root.mcSlide = 0;
_root.mcSpeed = 0;
}
} else if (Key.isDown(Key.RIGHT)) {
if (_root.mcMoving == false && _root.mcSliding == false) {
_root.mcMoving = true;
} else if (_root.mcMoving == true && _root.mcSliding == false) {
_root.p1Move("right",5);
}
} else if (!Key.isDown(Key.RIGHT)) {
if (_root.mcMoving == true && _root.mcSliding == false) {
_root.mcSliding = true;
} else if (_root.mcMoving == true && _root.mcSliding == true && _root.mcSlide<_root.mcMaxSpeed) {
_root.mcSlide += .2;
this._x += .2;
} else if (_root.mcMoving == true && _root.mcSliding == true && _root.mcSlide>=_root.mcMax) {
_root.mcMoving = false;
_root.mcSliding = false;
_root.mcSlide = 0;
_root.mcSpeed = 0;
}
}
};
I just don't get why when you press the left arrow its works completely fine, but when you press the right arrow it doesn't respond. It is literally the same code.
you never read it because of your loop code:
if(keyleft){
//catches all keyleft
}
else if(!keyleft){
//katches all non key left
}
else if(keyright){
//Never called because all eventualities have been covered by the above.
}
use if(keyright) instead of else if and it should work.
Related
I am new to Swift and I am using a 2D array for comparing and I need to get the row index once the condition is true but I got an error state that cannot invoke index with an argument list of type (of:Array<Float>)
My Code:
var entryCoordinate: [[Float]] = [[130.6,61.0],[167.5,61.0],[204.5,61.0],[243.6,61.0],[281.16,61.0],[315.3,61.0]]
for indexs in entryCoordinate
{
if indexs[0] == startPathPointX && indexs[1] == startPathPointY
{
let pathStartElement = indexs.index(of: indexs)
print(pathStartElement)
}
if indexs[0] == endPathPointX && indexs[1] == endPathPointY
{
let pathEndElement = indexs.index(of: indexs)
print(pathEndElement)
}
}
From your code with startPathPointY and endPathPointY you need to compare the second object from 2D array but you keep comparing the first one and you con use index(where:) with your array like this to get the pathStartElement and pathEndElement.
if let pathStartElement = entryCoordinate.index(where: { $0[0] == startPathPointX && $0[1] == startPathPointY }) {
print(pathStartElement)
}
if let pathEndElement = entryCoordinate.index(where: { $0[0] == endPathPointX && $0[1] == endPathPointY }) {
print(pathEndElement)
}
Try this code:
let myIndexPathStartElement = self.arrImagetData.index(where: { $0[0] == startPathPointX && $0[1] == startPathPointY })
let myIndexPathEndElement = self.arrImagetData.index(where: { $0[0] == endPathPointX && $0[1] == endPathPointY })
I want to make a while loop wait until a user clicks on a UILabel in a Swift Playground on Xcode. How can I do this?
Here's my loop
func gameLoop() {
while(score >= 0) {
let n = arc4random_uniform(3)
if(n == 0) {
opt1.text = rightStatements.randomElement()
opt2.text = wrongStatements.randomElement()
opt3.text = wrongStatements.randomElement()
} else if(n == 1) {
opt1.text = wrongStatements.randomElement()
opt2.text = rightStatements.randomElement()
opt3.text = wrongStatements.randomElement()
} else if(n == 2) {
opt1.text = wrongStatements.randomElement()
opt2.text = wrongStatements.randomElement()
opt3.text = rightStatements.randomElement()
}
}
}
For example, I want to wait until the user either clicks opt1, opt2, or opt3 Then do something based on what the user clicks.
Use Buttons instead of Labels and assign tag = 1, 2, and 3 for buttons. Create an IBAction function for the buttons and connect all the buttons to the same function.
Make variable 'n' as global.
var n = Int()
func nextAttempt() {
if(score >= 0) {
n = arc4random_uniform(3)
if(n == 0) {
opt1.text = rightStatements.randomElement()
opt2.text = wrongStatements.randomElement()
opt3.text = wrongStatements.randomElement()
} else if(n == 1) {
opt1.text = wrongStatements.randomElement()
opt2.text = rightStatements.randomElement()
opt3.text = wrongStatements.randomElement()
} else if(n == 2) {
opt1.text = wrongStatements.randomElement()
opt2.text = wrongStatements.randomElement()
opt3.text = rightStatements.randomElement()
}
}
else
{
//Score < 0
//Game Over
}
}
#IBAction func onButtonClick(_ sender: Any)
{
switch(sender.tag)
{
case 1:
if (n==0)
{
//Right button tapped
//Update score if you want
}
else
{
self.nextAttempt()
}
case 2:
if (n==1)
{
//Right button tapped
//Update score if you want
}
else
{
self.nextAttempt()
}
case 3:
if (n==2)
{
//Right button tapped
//Update score if you want
}
else
{
self.nextAttempt()
}
}
}
Hope this helps you!!
I made a PanGuesture as a slider, Here blow is the responds func:
func respondsToPenGesture(sender: UIPanGestureRecognizer) {
if (sender.state == UIGestureRecognizerState.Began) {
if noFilterEffectButton.selected == false {
startPanLocation = sender.locationInView(self.newEffectView)
persentageNumber.text = String(startNumber)
persentageNumber.hidden = false
}
} else if (sender.state == UIGestureRecognizerState.Changed) {
let stopLocation = sender.locationInView(self.newEffectView)
let abscissaChange = stopLocation.x - startPanLocation!.x
if newEffectView.hidden == false {
if abs(abscissaChange) > 0 {
if noFilterEffectButton.selected == false{
if let effectCurrent = self.currentEffect {
effectCurrent.adjustParams(CGFloat(abscissaChange/6))
}
}
}
if noFilterEffectButton.selected == false {
var printChangingNumber = startNumber + Int(abscissaChange)
if printChangingNumber > 100 {
printChangingNumber = 100
} else if printChangingNumber < 0 {
printChangingNumber = 0
}
persentageNumber.text = String(printChangingNumber)
}
}
} else if (sender.state == UIGestureRecognizerState.Ended) {
let stopLocation = sender.locationInView(self.newEffectView)
let abscissaChange = stopLocation.x - startPanLocation!.x
startNumber = startNumber + Int(abscissaChange)
if startNumber > 100 {
startNumber = 100
} else if startNumber < 0 {
startNumber = 0
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5*Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
self.persentageNumber.text = String(self.startNumber)
self.persentageNumber.hidden = true
}
}
}
percentageNumber is a label show the changes on the screen. And the adjustParams() function:
func adjustParams(value: CGFloat) {
newValue = value + newValue
self.adjust = newValue
print("AdjustNumber")
print(adjust)
}
And I override this function for exactly one effect:
override func adjustParams(value: CGFloat) {
super.adjustParams(value)
lastAutValueChange = lastAutValueChange + value/200
lastIntensityChange = lastIntensityChange + value/200
var currentAutValue = lastAutValueChange
var currentIntValue = lastIntensityChange
currentIntValue = currentIntValue < -1.0 ? -1.0 : currentIntValue
//value = value > 1.0 ? 1.0 : value
//autValue = value < -1.0 ? -1.0 : autValue
if (currentIntValue >= 0) {
currentIntValue = 1.0
} else {
currentIntValue += 1
}
if (currentAutValue <= 0) {
currentAutValue = 0
} else {
if currentAutValue > 1 {
currentAutValue = 1
}
}
print(currentIntValue)
print(currentAutValue)
self.autoTuneModule.setIntensity(Float(currentIntValue))
self.audioUnit.finalMix = Double(currentAutValue)
}
The test answer is not matchable for the exactly changes and the percentNumber shows on the screen. How could I change my functions to make them matchable for each others?
(By the way, I want to do something like the slider in Prisma, if there is something like it, please let me know about it).
import CoreMotion
var ButtonAudio4URL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Swing", ofType: "wav")!)
var ButtonAudioPlayer4 = AVAudioPlayer()
do {
try ButtonAudioPlayer4 = AVAudioPlayer(contentsOfURL: ButtonAudio4URL)
ButtonAudioPlayer4.prepareToPlay()
} catch {
print("audioPlayer failure")
}
func play() {
ButtonAudioPlayer4.currentTime = 0
ButtonAudioPlayer4.play()
}
func play2() {
ButtonAudioPlayer4.currentTime = 0
ButtonAudioPlayer4.play()
}
func play3() {
ButtonAudioPlayer4.currentTime = 0
ButtonAudioPlayer4.play()
}
func stop() {
ButtonAudioPlayer4.currentTime = 0
ButtonAudioPlayer4.stop()
}
func stop2() {
ButtonAudioPlayer4.currentTime = 0
ButtonAudioPlayer4.stop()
}
func stop3() {
ButtonAudioPlayer4.currentTime = 0
ButtonAudioPlayer4.stop()
}
lastDirection = 0 //Idle accel
threshold = 1.0 //Minimum positive(right) accel
nthreshold = -1.0 //Minimum negative(left) accel
if motionManager.accelerometerAvailable {
let queue = NSOperationQueue()
motionManager.startAccelerometerUpdatesToQueue(queue, withHandler: {
data, error in
guard let data = data else{
return
}
// Get the acceleration
let xAccel = data.acceleration.x //X accel
let yAccel = data.acceleration.y //Y accel
let zAccel = data.acceleration.z //Z accel
let xPositive = xAccel > 0 //Positive(right) x accel
let xNegative = xAccel < 0 //Negative(left) x accel
let yPositive = yAccel > 0 //Positive(up) y accel
let yNegative = yAccel < 0 //Negative(down) y accel
let zPositive = zAccel > 0 //Positive(front) z accel
let zNegative = zAccel < 0 //Negative(back) z accel
// Run if the acceleration is higher than theshold
if abs(xAccel) > self.threshold {
//If moved right
dispatch_async(dispatch_get_main_queue()) {
if self.lastDirection != 1 && xPositive {
self.lastDirection = 1
print("Up")
self.play()
} else if self.lastDirection != -1 && !xPositive {
self.lastDirection = -1
print("Down")
self.play()
}
}
}
// Run if the acceleration is higher than ntheshold
if abs(xAccel) < self.nthreshold {
//If moved left
dispatch_async(dispatch_get_main_queue()) {
if self.lastDirection != 1 && xNegative {
self.lastDirection = 1
print("Up")
self.play2()
} else if self.lastDirection != -1 && !xNegative {
self.lastDirection = -1
print("Down")
self.play2()
}
}
}
// Run if the acceleration is higher than theshold
if abs(yAccel) > self.threshold {
//If moved up
dispatch_async(dispatch_get_main_queue()) {
if self.lastDirection != 1 && yPositive {
self.lastDirection = 1
print("Up")
self.play()
} else if self.lastDirection != -1 && !yPositive {
self.lastDirection = -1
print("Down")
self.play()
}
}
}
// Run if the acceleration is higher than ntheshold
if abs(yAccel) < self.nthreshold {
//If moved left
dispatch_async(dispatch_get_main_queue()) {
if self.lastDirection != 1 && yNegative {
self.lastDirection = 1
print("Up")
self.play2()
} else if self.lastDirection != -1 && !yNegative {
self.lastDirection = -1
print("Down")
self.play2()
}
}
}
// Run if the acceleration is higher than theshold
if abs(zAccel) > self.threshold {
//If moved front
dispatch_async(dispatch_get_main_queue()) {
if self.lastDirection != 1 && zPositive {
self.lastDirection = 1
print("Up")
self.play()
} else if self.lastDirection != -1 && !zPositive {
self.lastDirection = -1
print("Down")
self.play()
}
}
}
// Run if the acceleration is higher than theshold
if abs(zAccel) < self.nthreshold {
//If moved back
dispatch_async(dispatch_get_main_queue()) {
if self.lastDirection != 1 && zNegative {
self.lastDirection = 1
print("Up")
self.play2()
} else if self.lastDirection != -1 && !zNegative {
self.lastDirection = -1
print("Down")
self.play2()
}
}
}
})
}
Hello,
I have built an iOS app with Xcode 7.2, Swift 2.0, for i0S 9.2
I would like to add a feature where when the user waves their device in the air, a sound will be played. My problem is that, although the sound plays, it suddenly stops, and is replayed when moved again in the process of playing the sound. I would like the sound to just be played once, without any overlapping or stopping. I have included all the code related to CoreMotion, and excluded all others.
Thank you.
If I do understand your purpose, you probably would like to have a boolean barrier to prevent duplicated playing.
Ex:
var isPlaying1 = false
func play() {
if self.isPlaying1 == true {
return
}
ButtonAudioPlayer4.currentTime = 0
ButtonAudioPlayer4.play()
self.isPlaying1 = true
}
func stop() {
if self.isPlaying1 == false {
return
}
ButtonAudioPlayer4.currentTime = 0
ButtonAudioPlayer4.stop()
self.isPlaying1 = false
}
I am writing a puzzle game for an IOS. In my code I need to fill an array with some random (and non-random numbers) that will represent the main data structure.
func Random(r : Range<Int>) -> Int {
return Int(arc4random_uniform(UInt32(r.endIndex - r.startIndex))) + r.startIndex
} // function to generate random number
var arrWithColors = [Int]() // array that will hold the numbers
//function to that check if an array contains a number in a range already
func checkForNumberInArrayWithRange(r: Range <Int>, n: Int ) -> Bool {
for i in r.startIndex..<r.endIndex {
if arrWithColors[i] == n { return true }
}
return false
}
// here is the main function where i keep getting stuck. Out of let's say five times it would only work 3 or even less.
func randHexWithTag() {
var rNumber : Int = Random(0...5)
for i in 0...5 {
while (true) {
rNumber = Random(0...5)
if !checkForNumberInArrayWithRange(0...5, n: rNumber) {
break
}
}
arrWithColors[i] = rNumber
}
arrWithColors[10] = arrWithColors[1]
for i in 6...11 {
while(true) {
rNumber = Random(0...5)
if ((rNumber == arrWithColors[0] && i == 9) || (rNumber == arrWithColors[2] && i == 11)) {
continue
}
if !checkForNumberInArrayWithRange(6...11, n: rNumber) {
break
}
}
if (i != 10) {
arrWithColors[i] = rNumber
}
}
arrWithColors[13] = arrWithColors[4]
for i in 12...17 {
while(true) {
rNumber = Random(0...5)
if (rNumber == arrWithColors[3] && i == 12) || (rNumber == arrWithColors[5] && i == 14) {
continue
}
if !checkForNumberInArrayWithRange(12...17, n: rNumber) {
break
}
}
if (i != 13) {
arrWithColors[i] = rNumber
}
}
}
The above code will ALWAYS fail during the first call to checkForNumberInArrayWithRange on this line:
if arrWithColors[i] == n { return true }
That is because arrWithColors is empty, and index i is out of range