Am trying to make a game, where I drag gems around.
The hierarchy is:
GameScene (this is the view controller)
gemBase, which holds the gems (light grey) SKSpriteNode
gems SKSpriteNode
The gems are children of gemBase, which is a child of GameScene.
When the gemBase is at 0,0 everything works fine when I drag the gems. They are in the same place I am touching the screen. But I want to offer a left-handed feature, where I offset the gemBase to the rightsize of the screen. All gems automatically move with the base so I don't need to recalculate their positions.
But then, when I try to move the gems, they are offset to the right of where I am touching the screen. They are offset by as much as I move the gemBase.
Below is my only code where I handle touchesMoved (in GameScene)
If you're having problems visualizing what I am describing, the screen shot is at:
http: // 98.7.37.117/ss.gif
Do I have to convert the touch.location?
override func touchesMoved(_ touches: SetUITouch, with event: UIEvent?){
guard touches.first != nil else { return }
if toggleHigh {highliteGem(theGem: myGems[0], clearAll: true)}
if let touch = touches.first, let node = myGV.currentGem, node.isMoving == true {
let touchLocation = touch.location(in: self)
node.moved = true
node.position = touchLocation
node.isMoving = true
node.inSlot = false
//addTrailToTwinkle(theNode: node)
}
}
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I've created a ball, and boxed my game scene.
The balls physics settings are:
self.physicsBody!.affectedByGravity = true
self.physicsBody!.restitution = 1.0
self.physicsBody!.linearDamping = 0
self.physicsBody!.friction = 0.3
self.physicsBody!.isDynamic = true
self.physicsBody!.mass = 0.5
self.physicsBody?.contactTestBitMask = bodyMasks.blankMask.rawValue
self.physicsBody?.collisionBitMask = bodyMasks.edgeMask.rawValue
self.physicsBody?.categoryBitMask = bodyMasks.ballMask.rawValue
When I box the game scene with:
self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
the ball bounces back up as intended.
However, if I replace edgeLoopFrom with my own custom borders:
yourLine.lineWidth = 5
yourLine.path = pathToDraw
yourLine.isUserInteractionEnabled = false
yourLine.strokeColor = .clear
yourLine.isHidden = false
yourLine.zPosition = 10
yourLine.physicsBody = SKPhysicsBody(edgeLoopFrom: pathToDraw)
yourLine.physicsBody?.affectedByGravity = false
yourLine.physicsBody?.pinned = true
yourLine.physicsBody?.categoryBitMask = bodyMasks.edgeMask.rawValue
yourLine.physicsBody?.collisionBitMask = bodyMasks.ballMask.rawValue
yourLine.physicsBody?.contactTestBitMask = bodyMasks.blankMask.rawValue
the ball just comes down with a thud, stops, and doesn't bounce.,
So am trying to figure out what physics settings I have to give to my custom made edges so that the ball bounces?
Hello, Just starting to learn Xcode and I can test the first chapter's app on my iPhone if it's conncted via USB-C. The book walks me through the part where I can allow Xcode to connect to the iPhone via WiFi, just checking "Connect via Network."Yet Xcode cannot find my phone unless it's connected via USB. When I go to Devices that checkbox stays checked, unless I unplug the phone it which case that box doesn't even appear.And yes, they are both on the same WiFi, it's the only one I have and it's up and running.Any thoughs?
In my app I create mutiple SKSpriteNodes, gems. Code snippet 1
When I loop through nodes from the main scene in a tap gesture, Code snippet 2, the gems register in a perfect square shape even though they are not. I have highlighted all areas that the orange gem registers in a tap as white. Here is the screen shot http://98.7.37.117/gem.png
Since the gem is itself not a square, I'd like to know if there is a way refine its shape so it would only show up in the list of nodes in UITapGestureRecognizer if the orange part is tapped. I have even tried by assigning it a physicsBody. But that made no difference.
Code Snippet 1
class MyGem : SKSpriteNode{
init(iColor : Gems) {
fileName = "\(iColor)_gem"
let skTexture = SKTexture(imageNamed: fileName)
super.init(texture: skTexture, color: .clear, size: .zero)
self.isHidden = true
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
self.size = CGSize(width: myGV.gemSize.width, height: myGV.gemSize.height)
self.zPosition = theZ.gem
self.position = CGPoint(x: 0, y: 0 )
self.isUserInteractionEnabled = false
self.name = "gem"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Code Snippet 2
@objc func tappedView(_ sender:UITapGestureRecognizer) {
if sender.state == .ended{
var post = sender.location(in: sender.view)
post = self.convertPoint(fromView: post)
for node in self.nodes(at: post){
if let touchNode = node as? MyGem
print("touched gem")
highliteGem(theGem: touchNode, clearAll: false)
return
}
Been using Xcode's Download Container for a short time, and at first there were no issues.
But lately, it doesn't always download all the files from my iPhone to the Mac. Sometimes cleaning the build folder works, other times not.
As well, the same happens whether I am connected to my iPhone via cable, or wifi.
Has anyone else had this issue?
Topic:
Developer Tools & Services
SubTopic:
Xcode
Haven't touched Xcode since it upgraded to 12.4. Just started a new app, which I planned to create without storyboards. But the default files I am used to deleting or manipulating aren't there anymore. I don't even see AppDelegate.swift.
So did Xcode 12.4 get rid of "storyboards" by default? And if so, where do I go to relearn how to start?
Thanks.
I just upgraded to Xcode 12.4, created a project using the "app" template, without SwiftUI, I chose Storyboard instead.
I placed a small image on the LaunchScreen.storyboard, and an NSLog output in my ViewController.
When I run the app on the simulator, the LaunchScreen does not, show, and I do get my NSLog output. So I know the app is running. When run this bare app on my physical iPhone X...I do get the launch screen.
So I opened a game app I started under Xcode 11.x. It will show the LaunchScreen on both simulator and my device.
I've checked that Launch screen interface file base name is set to LaunchScreen in Info.plist. It's also set under App Icons and Launch Images.
Is this some bug?
Expanding a speech to text demo, and while it works, I am still trying to learn Swift. Is .installTap the Swift version of a C callback function?
From what I interpret here, every time the buffer becomes full, the code in between the last { } runs, as well, the code below it is also run.
It almost feels like a callback combined with a GOTO line from basic.
yes, it works, but I'd like to understand that I am getting the flow of the code correctly.
func startSpeechRecognition (){
let node = audioEngine.inputNode
let recordingFormat = node.outputFormat(forBus: 0)
node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, _) in self.request.append(buffer) }
audioEngine.prepare()
do {
try audioEngine.start()
} catch let error {
...
}
guard let myRecognition = SFSpeechRecognizer() else {
...
return
}
if !myRecognition.isAvailable {
...
}
task = speechRecognizer?.recognitionTask(with: request, resultHandler: { (response, error) in guard let response = response else {
if error != nil {
print ("\(String(describing: error.debugDescription))")
} else {
print ("problem in repsonse")
}
return
}
let message = response.bestTranscription.formattedString
print ("\(message)")
})
}
New to Macs and still learning Swift. My first goal is a game so I actually am looking for TWO recommendations:Is there an advantage to Swift vs. Objective C when programming game apps?Can anyone recommend a decent book for beginners? I'm not a beginner, however my last heavy experience was with Perl, C, and the WindowsSDK. So am behind the times.Thank you
I have the code below which works just fine. getTwinklingGem returns type MyGem.
What I cannot figure out is if there is a proper syntax for writing the NOT into the if statement. Am still too new to Swift.
This works, but seems lengthy:
if let twinkling = getHighGem(), twinkling != nil
Is this the proper way to test for a nil return?
if let twinkling = getHighGem() as? MyGem
if let twinkling = getTwinklingGem() {
print ("not nil")
}
It's a small thing, but every time I open my current Xcode project the default iOS device to run my app on is my phone. Is there a way to change it to one of the simulators? i.e. iPhone Pro 11?
Xcode 13.3
Whenever I hit enter on Xcode, it starts off the new line with an indentation. It doesn't matter if I am creating a new line, or moving lines down, it always start the new line, or the moved line with an indentation.
This happens when I have:
Prefer Indent Using set to Tabs
regardless if I have
Syntax-Aware Indenting: Return checked or unchecked
Any thoughts?
Update, now somehow it does that auto indent on every line no matter whether I set it tabs or spaces. It's as if I broke it. Very annoying, please help!
Am trying to port away from .textLabel.text, as per Apple but I can't seem to find the way to get the text I set.
I now set my cells this way:
let cell = UITableViewCell()
var config = cell.defaultContentConfiguration()
config.text = dbClass.nameList[indexPath.row].clientName
config.textProperties.color = .black
config.textProperties.alignment = .center
cell.contentConfiguration = config
But when I try to get the text of a selected cell (once the user hits the OK button) I can't seem to reverse engineer how to get the text.
let cell = myClientList.cellForRow(at: myInvsList.indexPathForSelectedRow!)
let config = cell?.contentConfiguration
dbClass.curMasterinvList = ?????? (can't find what property to read here
I even tried
let config = cell?.defaultContentConfiguration()
Hoping that the text would be in there, but the text there is blank, so am assuming that's just the standard config before I've changed it.
I have Googled as much as possible, but can't seem to find this very simple need.
Am going through a SwiftUI course, so the code is not my own.
When I migrated my @Bindings into @Published items in an @ObservableObject I started getting the following error:
Publishing changes from within view updates is not allowed, this will cause undefined behavior.
The warning occurs in the ScannerView which is integrated with the main view, BarcodeScannerView. It occurs when an error occurs, and scannerView.alertItem is set to a value.
However, it does not occur when I am setting the value of scannerView.scannedCode, and as far as I can tell, they both come from the sample place, and are the same actions.
There are tons of posts like mine, but I have yet to find an answer. Any thoughts or comments would be very appreciated.
BarcodeScannerView
import SwiftUI
struct BarcodeScannerView: View {
@StateObject var viewModel = BarcodeScannerViewModel()
var body: some View {
NavigationStack {
VStack {
ScannerView(scannedCode: $viewModel.scannedCode, typeScanned: $viewModel.typeScanned, alertItem: $viewModel.alertItem)
.frame(maxWidth: .infinity, maxHeight: 300)
Spacer().frame(height: 60)
BarcodeView(statusText: viewModel.typeScanned)
TextView(statusText: viewModel.statusText, statusTextColor: viewModel.statusTextColor)
}
.navigationTitle("Barcode Scanner")
.alert(item: $viewModel.alertItem) { alertItem in
Alert(title: Text(alertItem.title), message: Text(alertItem.message), dismissButton: alertItem.dismissButton)
}
}
}
}
BarcodeScannerViewModel
import SwiftUI
final class BarcodeScannerViewModel: ObservableObject {
@Published var scannedCode = ""
@Published var typeScanned = "Scanned Barcode"
@Published var alertItem: AlertItem?
var statusText: String {
return scannedCode.isEmpty ? "Not Yet scanned" : scannedCode
}
var statusTextColor: Color {
scannedCode.isEmpty ? .red : .green
}
}
ScannerView
import SwiftUI
struct ScannerView: UIViewControllerRepresentable {
typealias UIViewControllerType = ScannerVC
@Binding var scannedCode : String
@Binding var typeScanned : String
@Binding var alertItem: AlertItem?
func makeCoordinator() -> Coordinator {
Coordinator(scannerView: self)
}
func makeUIViewController(context: Context) -> ScannerVC {
ScannerVC(scannerDelegate: context.coordinator)
}
func updateUIViewController(_ uiViewController: ScannerVC, context: Context) {
}
final class Coordinator: NSObject, ScannerVCDelegate {
private let scannerView: ScannerView
init(scannerView: ScannerView) {
self.scannerView = scannerView
}
func didFind(barcode: String, typeScanned: String) {
scannerView.scannedCode = barcode
scannerView.typeScanned = typeScanned
print (barcode)
}
func didSurface(error: CameraError) {
switch error {
case .invalidDeviceinput:
scannerView.alertItem = AlertContext.invalidDeviceInput
case .invalidScannedValue:
scannerView.alertItem = AlertContext.invalidScannedValue
case .invalidPreviewLayer:
scannerView.alertItem = AlertContext.invalidPreviewLayer
case .invalidStringObject:
scannerView.alertItem = AlertContext.invalidStringObject
}
}
}
}
My app needs a database and I would like to use SQLite.
Other than
using import SQLite3
and
adding libsqlite3.tbd in the Build Phase
Are there any other files I need to copy or import into my project?