I have a SKSpriteNode as a ball, it's been given all the SKPhysicsBody properties move around in all direction. What I want now is to make it unidirectional (only move in that direction it hasn't move to before and not go back in to a path it had move upon). Currently I have following thoughts on this the problem,
make a fieldBitMask, to the path that is iterated by it and repel
the ball to not go back
apply some kind of force/ impulses on the ball from touchesBegan/ touchesMoved method to keep it from going back
something that can be handled in update method
a lifesaver from stackflowoverflow, who is coding even on the weekend :)
Supporting Code snippets for better understanding,
//getting current touch position by using UIEvent methods
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {return}
let location = touch.location(in: self)
lastTouchPoint = location
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {return}
let location = touch.location(in: self)
lastTouchPoint = location
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
lastTouchPoint = nil
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
lastTouchPoint = nil
}
//ball created
func createPlayer(){
player = SKSpriteNode(imageNamed: "player")
player.position = CGPoint(x: 220, y: 420)
player.zPosition = 1
//physics for ball
player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.width / 2)
player.physicsBody?.allowsRotation = false
player.physicsBody?.linearDamping = 0.5
player.physicsBody?.categoryBitMask = collisionTypes.player.rawValue
player.physicsBody?.contactTestBitMask = collisionTypes.finish.rawValue
player.physicsBody?.collisionBitMask = collisionTypes.wall.rawValue
addChild(player)
}
//unwarp the optional property, calclulate the postion between player touch and current ball position
override func update(_ currentTime: TimeInterval) {
guard isGameOver == false else { return }
if let lastTouchPosition = lastTouchPoint {
//this usually gives a large value (related to screen size of the device) so /100 to normalize it
let diff = CGPoint(x: lastTouchPosition.x - player.position.x, y: lastTouchPosition.y - player.position.y)
physicsWorld.gravity = CGVector(dx: diff.x/100, dy: diff.y/100)
}
}
Well it was a combination little hacks in touchesBegan/ touchesMoved and update func,
First you need to catch on which touch occurred, get it's name (in my
case I made nodes which had alpha of 0, but become visible upon
moving over them i.e alpha 1). In touchesBegan, touchesMoved as follow
guard let touch = touches.first else {return}
let location = touch.location(in: self)
lastTouchPoint = location
let positionInScene = touch.location(in: self)
let touchedNode = self.atPoint(positionInScene)
if let name = touchedNode.name
{
if name == "vortex"
{
touching = false
self.view!.isUserInteractionEnabled = false
print("Touched on the interacted node")
}else{
self.view!.isUserInteractionEnabled = true
touching = true
}
}
}
Second use a BOOL touching to track user interactions, on the screen by using getting a tap recogniser setup, as follow
func setupTapDetection() {
let t = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
view?.addGestureRecognizer(t)
}
#objc func tapped(_ tap: UITapGestureRecognizer) {
touching = true
}
Finally in update put checks as follow,
guard isGameOver == false else { return }
self.view!.isUserInteractionEnabled = true
if(touching ?? true){
if let lastTouchPosition = lastTouchPoint {
//this usually gives a large value (related to screen size of the device) so /100 to normalize it
let diff = CGPoint(x: lastTouchPosition.x - player.position.x, y: lastTouchPosition.y - player.position.y)
physicsWorld.gravity = CGVector(dx: diff.x/100, dy: diff.y/100)
}
}
}
Related
With my current code, the node is extremely laggy, and moves or teleports in random directions for some reason when its flicked. How can i fix this, and also can someone explain why it is teleporting and moving to random places in the scene.
Also, is there anyway to allow the node to be moved only when it is dragged from its position, rather than being at the gesturerecognizer's coordinates at all times?
override func didMove(to view: SKView) {
let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.pan(_:)))
view.addGestureRecognizer(gestureRecognizer)
circleNode.physicsBody = SKPhysicsBody(circleOfRadius: 20)
self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
self.addChild(circleNode)
}
#objc func pan(_ recognizer: UIPanGestureRecognizer) {
if recognizer.state == .changed {
self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
var location = recognizer.location(in: self.view!)
location = self.convertPoint(fromView: location)
circleNode.position = location
}
if recognizer.state == .ended {
self.physicsWorld.gravity = CGVector(dx: 0, dy: -9.8)
let transformerX = 1024/self.view!.frame.size.width
let transformerY = 768/self.view!.frame.size.height
let velocity = recognizer.velocity(in: self.view)
circleNode.physicsBody?.applyForce(CGVector(dx: velocity.x * transformerX, dy: velocity.y * transformerY))
}
}
Here is some code I was playing around with. I'm able to drag and flick a spear (spear Image) and also "pop" a pig head. This is the whole GameScene.Remove the code you don't need. :)
import SpriteKit
import CoreMotion
class GameScene: SKScene, SKPhysicsContactDelegate {
enum CollisionTypes: UInt32{
case spear = 1
case wall = 2
case head = 4
}
var touchPoint: CGPoint = CGPoint()
var touching: Bool = false
override func didMove(to view: SKView) {
self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
//Add contact delegate
physicsWorld.contactDelegate = self
self.backgroundColor = .white
self.addChild(spearNode)
self.addChild(headNode)
}
lazy var spearNode: SKSpriteNode = {
let node = SKSpriteNode(imageNamed: "spear2")
node.name = "Spear"
node.physicsBody = SKPhysicsBody(texture: node.texture!,
size: CGSize(width: node.frame.width , height: node.frame.height))
node.position = CGPoint(x:self.frame.midX , y:self.frame.midY)
node.physicsBody?.affectedByGravity = true
node.physicsBody?.allowsRotation = false
node.size = CGSize(width: node.frame.width , height: node.frame.height )
node.physicsBody?.categoryBitMask = CollisionTypes.spear.rawValue
node.physicsBody?.contactTestBitMask = CollisionTypes.head.rawValue
node.physicsBody?.collisionBitMask = CollisionTypes.head.rawValue
return node
}()
lazy var headNode: SKSpriteNode = {
let node = SKSpriteNode(imageNamed: "Pig")
node.name = "Pig"
node.physicsBody = SKPhysicsBody(texture: node.texture!,
size: CGSize(width: node.frame.width , height: node.frame.height))
node.position = CGPoint(x:self.frame.midX , y:self.frame.maxY - 100)
node.physicsBody?.affectedByGravity = true
node.physicsBody?.allowsRotation = false
node.size = CGSize(width: node.frame.width / 2 , height: node.frame.height / 2 )
node.physicsBody?.categoryBitMask = CollisionTypes.head.rawValue
return node
}()
func didBegin(_ contact: SKPhysicsContact){
guard let nodeA = contact.bodyA.node else {return}
guard let nodeB = contact.bodyB.node else {return}
print("Contacted")
if nodeA.name == "Pig" && nodeB.name == "Spear"{
nodeA.removeFromParent()
}
if nodeA.name == "Spear" && nodeB.name == "Pig"{
nodeB.removeFromParent()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first!
let location = touch.location(in:self)
if spearNode.frame.contains(location) {
touchPoint = location
touching = true
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first!
let location = touch.location(in: self)
touchPoint = location
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
touching = false
}
override func update(_ currentTime: TimeInterval) {
physicsWorld.gravity = CGVector(dx:0, dy: -9.8)
if touching {
let dt:CGFloat = 1.0/60.0
let distance = CGVector(dx: touchPoint.x-spearNode.position.x, dy: touchPoint.y-spearNode.position.y)
let velocity = CGVector(dx: distance.dx/dt, dy: distance.dy/dt)
spearNode.physicsBody!.velocity=velocity
}
}
}
Why not simply impart a force to the object based upon the swipe gesture rather than turning off gravity, manually moving the object, and then turning on gravity again when the swipe is over?
I have an SKSpriteNode in which I've set the centerRect property so that the node can be stretched to appear like a styled line. My intention is for the user to touch the screen, and draw/drag a straight line with the node. The line would pivot around an anchor point to remain straight.
In touchesBegan:, the node is added:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let positionInScene = touch.location(in: self)
if let _ = fgNode.childNode(withName: "laser") {
print("already there")
} else {
laser.centerRect = CGRect(x: 0.42857143, y: 0.57142857, width: 0.14285714, height: 0.14285714)
laser.anchorPoint = CGPoint(x: 0, y: 0.5)
laser.position = positionInScene
fgNode.addChild(laser)
}
}
And adjusted in touchesMoved::
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let positionInScene = touch.location(in: self)
stretchLaserTo(positionInScene)
}
The node is stretched and rotated with two functions:
func stretchLaserTo(_ point: CGPoint) {
let offset = point - laser.anchorPoint
let length = offset.length()
let direction = offset / CGFloat(length)
laser.xScale = length
rotate(sprite: laser, direction: direction)
}
func rotate(sprite: SKSpriteNode, direction: CGPoint) {
sprite.zRotation = atan2(direction.y, direction.x)
}
I think I'm somewhat on the right track. The line rotates with my touch and expands, however, it's extremely sensitive and doesn't stay with my touch. Maybe I'm going about it wrong. Is there a standard technique for doing something like this?
An example of this working can be seen here: https://imgur.com/A83L45i
I suggest you set anchor point of the sprite to (0, 0), set the sprite's scale to the distance between the sprite's position and the current touch location, and then rotate the sprite.
First, create a sprite and set its anchor point.
let laser = SKSpriteNode(color: .white, size: CGSize(width: 1, height: 1))
override func didMove(to view: SKView) {
laser.anchorPoint = CGPoint(x: 0, y: 0)
addChild(laser)
}
In touchesBegan, set the position of the sprite to the location of the touch. In this case, it's also the start of the line.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let positionInScene = touch.location(in: self)
laser.position = positionInScene
laser.setScale(1)
}
Update the sprite so that it forms a line that starts at the position of the sprite and ends at the current touch location.
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let positionInScene = touch.location(in: self)
stretchLaserTo(positionInScene)
}
Stretch the sprite by setting its xScale to the distance from the start of the line to the location of the current touch and then rotate the sprite.
func stretchLaserTo(_ point: CGPoint) {
let dx = point.x - laser.position.x
let dy = point.y - laser.position.y
let length = sqrt(dx*dx + dy*dy)
let angle = atan2(dy, dx)
laser.xScale = length
laser.zRotation = angle
}
I am trying to detect collision contactPoint between existing line and line which user currently drawing using finger.
Here is my code :
let padding: CGFloat = 100
override func didMove(to view: SKView) {
physicsWorld.contactDelegate = self
let startPoint1 = CGPoint(x: self.frame.minX + padding , y: self.frame.minY + padding)
let leftHorizontalPoint = CGPoint(x: self.frame.minX + padding, y: self.frame.maxY - padding)
let line1 = SKShapeNode()
let line_path:CGMutablePath = CGMutablePath()
line_path.move(to: startPoint1)
line_path.addLine(to: leftHorizontalPoint)
line1.path = line_path
line1.lineWidth = 3
line1.strokeColor = UIColor.white
addChild(line1)
line1.physicsBody = SKPhysicsBody(edgeLoopFrom: line1.frame)
line1.physicsBody?.isDynamic = true
line1.physicsBody?.categoryBitMask = PhysicsCategory.solidLine
line1.physicsBody?.collisionBitMask = PhysicsCategory.currentLine
line1.physicsBody?.contactTestBitMask = PhysicsCategory.currentLine
}
Then on touchBegin, touchMove & touchEnd I am having following code :
var currentLineNode: SKShapeNode!
var startPoint: CGPoint = CGPoint.zero
func touchDown(atPoint pos : CGPoint) {
startPoint = pos
}
func touchMoved(toPoint pos : CGPoint) {
if currentLineNode != nil {
currentLineNode.removeFromParent()
}
currentLineNode = SKShapeNode()
currentLineNode.zPosition = 1
let line_path:CGMutablePath = CGMutablePath()
line_path.move(to: startPoint)
line_path.addLine(to: pos)
currentLineNode.path = line_path
currentLineNode.lineWidth = 3
currentLineNode.strokeColor = UIColor.red
addChild(currentLineNode)
currentLineNode.physicsBody = SKPhysicsBody(edgeLoopFrom: currentLineNode.frame)
currentLineNode.physicsBody?.isDynamic = true
currentLineNode.physicsBody?.categoryBitMask = PhysicsCategory.currentLine
currentLineNode.physicsBody?.collisionBitMask = PhysicsCategory.solidLine
currentLineNode.physicsBody?.contactTestBitMask = PhysicsCategory.solidLine
}
func touchUp(atPoint pos : CGPoint) {
if currentLineNode != nil {
currentLineNode.removeFromParent()
}
currentLineNode = SKShapeNode()
let line_path:CGMutablePath = CGMutablePath()
line_path.move(to: startPoint)
line_path.addLine(to: pos)
currentLineNode.path = line_path
currentLineNode.lineWidth = 3
currentLineNode.strokeColor = UIColor.red
addChild(currentLineNode)
currentLineNode.physicsBody = SKPhysicsBody(edgeLoopFrom: currentLineNode.frame)
currentLineNode.physicsBody?.isDynamic = true
currentLineNode.physicsBody?.categoryBitMask = PhysicsCategory.currentLine
currentLineNode.physicsBody?.collisionBitMask = PhysicsCategory.solidLine
currentLineNode.physicsBody?.contactTestBitMask = PhysicsCategory.solidLine
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
physicsWorld's contactDelegate as follow : (Delegate not even executed)
extension GameScene : SKPhysicsContactDelegate {
func didBegin(_ contact: SKPhysicsContact) {
// This never get detected :(
print(contact.contactPoint)
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
}
}
Here is my output where even though passing from white colored line its not detecting collision.
What could be wrong? Any suggestion on this will be helpful.
You are using 2 edge based bodies. Edge based bodies will always be isDynamic = false no matter if you set it or not. You need at least 1 volume based body to be able to perform a contact.
Plus on top of that you are constantly removing and adding a node, which is a terrible idea.
I would recommend adding your node on the touchesBegan only, then update only the path on touchesMoved
you are creating your physics body with an edge loop. Apple defines edge loops as...
An edge has no volume or mass and is always treated as if the isDynamic property is equal to false. Edges may only collide with volume-based physics bodies.
changing your physics body to this works
currentLineNode.physicsBody = SKPhysicsBody(rectangleOf: currentLineNode.frame.size, center: CGPoint(x: startPoint.x + currentLineNode.frame.size.width / 2, y: startPoint.y + currentLineNode.frame.size.height / 2))
also should be noted that changing your physics body in touchesEnded is redundant and adds nothing. I removed it from touchesEnded and it works fine
override func didMove(to view: SKView) {
view.scene?.anchorPoint = CGPoint(x: 0,y : 0)
castle = SKShapeNode(circleOfRadius: ballRadius1)
castle.physicsBody = SKPhysicsBody(circleOfRadius:ballRadius1)
castle.fillColor = .white
castle.name = "castle"
castle.position = CGPoint(x: 0, y: 0)
castle.physicsBody?.isDynamic = false
castle.physicsBody?.affectedByGravity = false;
castle.isUserInteractionEnabled = true
self.addChild(castle)
I have a circle in the middle of the screen, I want to make it disappear when I tap it. Can you please help me? It is an SKShapeNode and has a PhysicsBody with the same radius
You could use touchesBegan and make it look like so
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches{
let pointOfTouch = touch.location(in: self)
let nodeITapped = atPoint(pointOfTouch)
let nameOfTappedNode = nodeITapped.name
if nameOfTappedNode == "castle"{
//make it do whatever you want
castle.removeFromParent()
}
}
}
you could also implement it in touchesEnded instead if you want the node to disappear as soon as the user releases the touch.
i want to move my character in scene kit .i have a map as at github Fpscontroller and i want my character move in this map but when ever i touch to move character it jumps and don,t know where is goes here is my code.`
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
if CGRectContainsPoint(gameView.virtualDPadBounds(), touch.locationInView(gameView)) {
if padTouch == nil {
padTouch = touch
controllerStoredDirection = float2(0.0)
}
} else if panningTouch == nil {
panningTouch = touches.first
}
if padTouch != nil && panningTouch != nil {
break
}
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = panningTouch {
let displacement = (float2(touch.locationInView(view)) - float2(touch.previousLocationInView(view)))
panCamera(displacement)
}
if let touch = padTouch {
let displacement = (float2(touch.locationInView(view)) - float2(touch.previousLocationInView(view)))
controllerStoredDirection = clamp(mix(controllerStoredDirection, displacement, t: ViewController.controllerAcceleration), min: -ViewController.controllerDirectionLimit, max: ViewController.controllerDirectionLimit)
}
}
func commonTouchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = panningTouch {
if touches.contains(touch) {
panningTouch = nil
}
}
if let touch = padTouch {
if touches.contains(touch) || event?.touchesForView(view)?.contains(touch) == false {
padTouch = nil
controllerStoredDirection = float2(0.0)
}
}
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
commonTouchesEnded(touches!, withEvent: event)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
commonTouchesEnded(touches, withEvent: event)
}
i followed apple fox example for moving with touch and in my viewcontroller
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func walkGestureRecognized(gesture: UIPanGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.Ended || gesture.state == UIGestureRecognizerState.Cancelled {
gesture.setTranslation(CGPointZero, inView: self.view)
}
}
func renderer(aRenderer: SCNSceneRenderer, updateAtTime time: NSTimeInterval) {
//get walk gesture translation
let translation = walkGesture.translationInView(self.view)
//create impulse vector for hero
let angle = heroNode.presentationNode.rotation.w * heroNode.presentationNode.rotation.y
var impulse = SCNVector3(x: max(-1, min(1, Float(translation.x) / 50)), y: 0, z: max(-1, min(1, Float(-translation.y) / 50)))
impulse = SCNVector3(
x: impulse.x * cos(angle) - impulse.z * sin(angle),
y: 0,
z: impulse.x * -sin(angle) - impulse.z * cos(angle)
)
heroNode.physicsBody?.applyForce(impulse, impulse: true)
let scene = gameView.scene!
let direction = characterDirection()
let groundNode = character.walkInDirection(direction, time: time, scene: scene, groundTypeFromMaterial:groundTypeFromMaterial)
setting character position and direction....
private func characterDirection() -> float3 {
let controllerDirection = self.controllerDirection()
var direction = float3(controllerDirection.x, 0.0, controllerDirection.y)
if let pov = gameView.pointOfView {
let p1 = pov.presentationNode.convertPosition(SCNVector3(direction), toNode: nil)
let p0 = pov.presentationNode.convertPosition(SCNVector3Zero, toNode: nil)
direction = float3(Float(p1.x - p0.x), 0.0, Float(p1.z - p0.z))
if direction.x != 0.0 || direction.z != 0.0 {
direction = normalize(direction)
}
}
return direction
}
there are actually two scenes called in view controller class one is empty scene called for mapNode as hereoNode and other is character sceneNode
let scene = SCNScene()
scene.rootNode.addChildNode(heroNode)
let personScene = SCNScene(named: "game.scnassets/person.scn")!
personNode = personScene.rootNode.childNodeWithName("person", recursively: true)
personNode?.position = SCNVector3(x:4.5,y:0,z:25)
node.addChildNode(personNode)
scene.rootNode.addChildNode(character.node)
i am updating my question with some more details as you can see in this screen shot image i m attatching here enter image description here i want to move this fox in map with touch but it is not working it just jump and go out from map when i touch .....plz someone tell me where is my fault in code