Swift adding Launch Screen cause main app screen to preform odd - xcode
This is with out launch screen.
This is with launch screen.
Any thoughts on what I might have done wrong?
Ok I had paste in sections because it would complain about the format other wise.
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate
var bird: SKSpriteNode = SKSpriteNode()
var overlay: SKSpriteNode = SKSpriteNode()
var scoreLabel: SKLabelNode = SKLabelNode(fontNamed: "System-Bold")
var ground1: SKSpriteNode = SKSpriteNode()
var ground2: SKSpriteNode = SKSpriteNode()
var background1: SKSpriteNode = SKSpriteNode()
var background2: SKSpriteNode = SKSpriteNode()
var mainPipe: Pipe = Pipe()
var pipes: [Pipe] = []
var space: Float = 90
var prevNum: Float = 0
var maxRange: Float = 175
var minRange: Float = -100
var birdCategory: UInt32 = 1
var pipeCategory: UInt32 = 2
var score: Int = 0
var movingSpeed: CGFloat = 3.3
var isMoving: Bool = false
var isGroundMoving: Bool = true
override func didMoveToView(view: SKView)
mainPipe = Pipe(color: UIColor.blackColor(), size: CGSize(width: view.bounds.size.width / 6, height: view.bounds.size.height))
overlay = SKSpriteNode(color: UIColor.grayColor(), size: self.view!.bounds.size)
overlay.alpha = 0.7
overlay.zPosition = 11
overlay.position.x += overlay.size.width / 2
overlay.position.y += overlay.size.height / 2
background1 = SKSpriteNode(imageNamed: "Background")
background2 = SKSpriteNode(imageNamed: "Background")
background1.position.x = view.bounds.size.width * 0.5
background2.position.x = view.bounds.size.width * 1.5
background1.position.y = view.bounds.size.height * 0.5
background2.position.y = view.bounds.size.height * 0.5
background1.texture!.filteringMode = SKTextureFilteringMode.Nearest
background2.texture!.filteringMode = SKTextureFilteringMode.Nearest
ground1 = SKSpriteNode(imageNamed: "Ground")
ground2 = SKSpriteNode(imageNamed: "Ground")
ground1.size.width = view.bounds.size.width + 2
ground2.size.width = view.bounds.size.width + 2
ground1.position.x = view.bounds.size.width * 0.5
ground2.position.x = view.bounds.size.width * 1.5
ground1.position.y = ground1.size.height * 0.4
ground2.position.y = ground2.size.height * 0.4
ground1.physicsBody = SKPhysicsBody(rectangleOfSize: ground1.size)
ground2.physicsBody = SKPhysicsBody(rectangleOfSize: ground2.size)
ground1.physicsBody!.dynamic = false
ground2.physicsBody!.dynamic = false
ground1.zPosition = 10
ground2.zPosition = 10
ground1.texture!.filteringMode = SKTextureFilteringMode.Nearest
ground2.texture!.filteringMode = SKTextureFilteringMode.Nearest
bird.physicsBody = SKPhysicsBody(circleOfRadius: 8)
bird.physicsBody!.dynamic = false
bird.physicsBody!.contactTestBitMask = pipeCategory
bird.physicsBody!.collisionBitMask = pipeCategory
bird.zPosition = 9
//bird.lineWidth = 0
bird = SKSpriteNode(imageNamed: "jennaface")
//bird.fillColor = UIColor.redColor()
bird.physicsBody = SKPhysicsBody(circleOfRadius: bird.size.width / 2.5)
bird.position = CGPoint(x: 150, y: view.bounds.height / 2 - 10)
scoreLabel.position.x = 13
scoreLabel.position.y = view.bounds.height - 50
scoreLabel.text = "Score: 0"
scoreLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Left
scoreLabel.hidden = true
self.physicsWorld.contactDelegate = self;
self.physicsWorld.gravity = CGVectorMake(0, -3.5)
self.addChild(background1)
self.addChild(background2)
self.addChild(ground1)
self.addChild(ground2)
self.addChild(bird)
self.addChild(scoreLabel)
func spawnPipeRow(offs: Float)
{
let offset = offs - space / 2
let pipeBot = mainPipe.copy() as Pipe
let pipeTop = mainPipe.copy() as Pipe
pipeBot.texture = SKTexture(imageNamed: "BotPipe")
pipeTop.texture = SKTexture(imageNamed: "TopPipe")
pipeBot.texture!.filteringMode = SKTextureFilteringMode.Nearest
pipeTop.texture!.filteringMode = SKTextureFilteringMode.Nearest
pipeBot.isBottom = true
let xx = Float(self.view!.bounds.size.width)
self.setPositionRelativeBot(pipeBot, x: xx, y: offset)
self.setPositionRelativeTop(pipeTop, x: xx, y: offset + space)
pipeBot.physicsBody = SKPhysicsBody(rectangleOfSize: pipeBot.size)
pipeTop.physicsBody = SKPhysicsBody(rectangleOfSize: pipeTop.size)
pipeBot.physicsBody!.dynamic = false
pipeTop.physicsBody!.dynamic = false
pipeBot.physicsBody!.contactTestBitMask = birdCategory
pipeTop.physicsBody!.contactTestBitMask = birdCategory
pipeBot.physicsBody!.collisionBitMask = birdCategory
pipeTop.physicsBody!.collisionBitMask = birdCategory
pipes.append(pipeBot)
pipes.append(pipeTop)
self.addChild(pipeBot)
self.addChild(pipeTop)
}
func setPositionRelativeBot(node: SKSpriteNode, x: Float, y: Float)
{
let xx = (Float(node.size.width) / 2) + x
let yy = Float(self.view!.bounds.size.height) / 2 - (Float(node.size.height) / 2) + y
node.position.x = CGFloat(xx)
node.position.y = CGFloat(yy)
}
func setPositionRelativeTop(node: SKSpriteNode, x: Float, y: Float)
{
let xx = (Float(node.size.width) / 2) + x
let yy = Float(self.view!.bounds.size.height) / 2 + (Float(node.size.height) / 2) + y
node.position.x = CGFloat(xx)
node.position.y = CGFloat(yy)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
{
if (!bird.physicsBody!.dynamic)
{
//First touch
self.spawnPipeRow(0)
bird.physicsBody!.dynamic = true
bird.physicsBody!.velocity = CGVectorMake(0, 175)
scoreLabel.hidden = false
isMoving = true
} else if (isMoving)
{
var vel: CGFloat = 200
if (self.view!.bounds.size.height - bird.position.y < 85)
{
vel -= 85 - (self.view!.bounds.size.height - bird.position.y)
}
bird.physicsBody!.velocity = CGVectorMake(0, vel)
} else
{
overlay.removeFromParent()
for pi in pipes
{
pi.removeFromParent()
}
pipes.removeAll(keepCapacity: false)
score = 0
bird.physicsBody!.dynamic = false
bird.position = CGPoint(x: 150, y: view!.bounds.size.height / 2 - 10)
scoreLabel.hidden = true
isGroundMoving = true
}
}
override func update(currentTime: CFTimeInterval)
{
if (isGroundMoving)
{
ground1.position.x -= movingSpeed
ground2.position.x -= movingSpeed
if (ground1.position.x <= -self.view!.bounds.size.width / 2)
{
ground1.position.x = self.view!.bounds.size.width * 1.5 - 2
}
if (ground2.position.x <= -self.view!.bounds.size.width / 2)
{
ground2.position.x = self.view!.bounds.size.width * 1.5 - 2
}
background1.position.x -= movingSpeed / 3
background2.position.x -= movingSpeed / 3
if (background1.position.x <= -self.view!.bounds.size.width / 2)
{
background1.position.x = self.view!.bounds.size.width * 1.5 - 2
}
if (background2.position.x <= -self.view!.bounds.size.width / 2)
{
background2.position.x = self.view!.bounds.size.width * 1.5 - 2
}
if (isMoving)
{
for (var i = 0; i < pipes.count; i++)
{
let pipe = pipes[i]
if (pipe.position.x + (pipe.size.width / 2) < 0)
{
pipe.removeFromParent()
continue
}
if (pipe.position.x + (pipe.size.width / 2) < self.view!.bounds.size.width / 2 && pipe.isBottom && !pipe.pointAdded)
{
score++
pipe.pointAdded = true
}
pipe.position.x -= movingSpeed
if (i == pipes.count - 1)
{
if (pipe.position.x < self.view!.bounds.width - pipe.size.width * 2.0)
{
self.spawnPipeRow(self.randomOffset())
}
}
}
scoreLabel.text = "Score: \(score)"
}
}
}
func didBeginContact(contact: SKPhysicsContact!)
{
if (isMoving)
{
isMoving = false
isGroundMoving = false
bird.physicsBody!.velocity = CGVectorMake(0, 0)
for pi in pipes
{
pi.physicsBody = nil
}
self.addChild(overlay)
} else
{
bird.physicsBody!.velocity = CGVectorMake(0, 0)
}
}
func randomOffset() -> Float
{
let max = maxRange - prevNum
let min = minRange - prevNum
var rNum: Float = Float(arc4random() % 61) + 40 //40 - 100
var rNum1: Float = Float(arc4random() % 31) + 1
if (rNum1 % 2 == 0)
{
var tempNum = prevNum + rNum
if (tempNum > maxRange)
{
tempNum = maxRange - rNum
}
rNum = tempNum
} else
{
var tempNum = prevNum - rNum
if (tempNum < minRange)
{
tempNum = minRange + rNum
}
rNum = tempNum
}
prevNum = rNum
return rNum
}
class Pipe: SKSpriteNode
{
var isBottom: Bool = false
var pointAdded: Bool = false
}
Related
Detect collision between the player and an object with Sprite kit
I am making a game with sprite kit in xcode and i want let the game finish when the player touch the monster, do you know how to use categorymask? here is part of the code : import SpriteKit import GameplayKit import CoreMotion class GameScene: SKScene, SKPhysicsContactDelegate { var player : SKSpriteNode! var playerCategory : UInt32 = 0x1 << 0 var gameTimer2 : Timer! var possiblealien = ["alien", "alien2", "alien3"] let alienCategory : UInt32 = 0x1 << 1 override func didMove(to view: SKView) { player = SKSpriteNode (imageNamed: "player") player.position = CGPoint (x: self.frame.size.width / 2 - 500 , y: player.size.height / 2 - 560) player.size = CGSize(width: player.size.width * 6 , height: player.size.height * 6) self.addChild(player) player.zPosition = 2 self.physicsWorld.gravity = CGVector (dx: 0 , dy: 0 ) self.physicsWorld.contactDelegate = self player.physicsBody?.contactTestBitMask = playerCategory player.physicsBody? = SKPhysicsBody(rectangleOf: player.size) player.physicsBody?.isDynamic = true player.physicsBody?.categoryBitMask = monsterCategory player.physicsBody?.collisionBitMask = 0 gameTimer2 = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(addalien), userInfo: nil, repeats: true) motionManager.accelerometerUpdateInterval = 0.2 motionManager.startAccelerometerUpdates(to: OperationQueue.current!) { ( data: CMAccelerometerData?, error:Error?)in if let accelerometerData = data { let acceleration = accelerometerData.acceleration self.xAcceleration = CGFloat(acceleration.x) * 0.65 + self.xAcceleration * 0.25 } } #objc func addalien () { possiblealien = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: possiblealien) as! [String] let alien = SKSpriteNode(imageNamed: possiblealien[0]) let randomalienposition = GKRandomDistribution(lowestValue: -480, highestValue: +800 ) let position = CGFloat(randomalienposition.nextInt()) alien.position = CGPoint (x: position - 200 , y: self.frame.size.height * 0.5 + alien.size.height) alien.physicsBody = SKPhysicsBody(rectangleOf: alien.size) alien.physicsBody?.isDynamic = true alien.physicsBody?.categoryBitMask = alienCategory alien.physicsBody?.contactTestBitMask = playerCategory alien.physicsBody?.collisionBitMask = 0 alien.zPosition = 2 alien.size = CGSize(width: alien.size.width * 1 , height: alien.size.height * 1) self.addChild(alien) let animationduration:TimeInterval = 6 var actionArray = [SKAction]() actionArray.append(SKAction.move(to: CGPoint(x: position, y: -1000 ),duration: animationduration)) actionArray.append(SKAction.removeFromParent()) alien.run(SKAction.sequence(actionArray)) }
I see your problem, you need to declare it's physics body in a Physics Category, Otherwise, there would be no body for it at all struct PhysicsCategory { static let None:UInt32 = 0 static let All:UInt32 = UInt32.max static let Player:UInt32 = 0b1 Also, The contactbitmasks should be what they will collide with along with collisiontestbitmask. catergorybitmask should be the category of the sprite in the struct ex: let alien = SKSpritenode() alien.physicsBody?.categoryBitMask = PhysicsCategory.Alien alien.physicsBody?.contactBitMask = PhysicsCategory.Player alien.physicsBody?.collisionTestBitMask = PhysicsCategory.Player Also, you can use | to declare if they will collide with multiple things
Drag ball over the circle in iOS.Xamarin (monotouch)
I am beginner in Xamarin iOS platform. I want the drag ball over the circle border. Please find below image for more details. Thanks in advance :)
I just convert the Swift to C# , origin code here. nfloat midViewX; nfloat midViewY; UIBezierPath circlePath2; CAShapeLayer shapeLayer2 = new CAShapeLayer(); public override void ViewDidLoad() { base.ViewDidLoad(); midViewX = UIScreen.MainScreen.Bounds.Width / 2; midViewY = UIScreen.MainScreen.Bounds.Height / 2; var circlePath = UIBezierPath.FromArc(new CGPoint(midViewX, midViewY), 100, 0, (nfloat)(Math.PI*2), true); var shapeLayer = new CAShapeLayer(); shapeLayer.Path = circlePath.CGPath; shapeLayer.FillColor = UIColor.Clear.CGColor; shapeLayer.StrokeColor = UIColor.Red.CGColor; shapeLayer.LineWidth = 3; View.Layer.AddSublayer(shapeLayer); var angleEarthAfterCalculate = (nfloat)(180 * Math.PI / 180 - Math.PI / 2); var earthX = midViewX + Math.Cos(angleEarthAfterCalculate) * 100; var earthY = midViewY + Math.Sin(angleEarthAfterCalculate) * 100; circlePath2 = UIBezierPath.FromArc(new CGPoint(earthX, earthY), 10, 0, (nfloat)(Math.PI * 2), true); shapeLayer2.Path = circlePath2.CGPath; shapeLayer2.FillColor = UIColor.Blue.CGColor; shapeLayer2.StrokeColor = UIColor.Clear.CGColor; shapeLayer2.LineWidth = 7; View.Layer.AddSublayer(shapeLayer2); var dragBall = new UIPanGestureRecognizer(DragBall); View.AddGestureRecognizer(dragBall); } void DragBall(UIPanGestureRecognizer recognizer) { var point = recognizer.LocationInView(View); var earthX = point.X; var earthY = point.Y; var midViewXDouble = midViewX; var midViewYDouble = midViewY; var angleX = earthX - midViewXDouble; var angleY = earthY - midViewYDouble; var angle = Math.Atan2(angleY, angleX); var earthX2 = midViewXDouble + Math.Cos(angle) * 100; var earthY2 = midViewYDouble + Math.Sin(angle) * 100; circlePath2 = UIBezierPath.FromArc(new CGPoint(earthX2, earthY2), 10, 0, (nfloat)(Math.PI * 2), true); shapeLayer2.Path = circlePath2.CGPath; }
Image transformation matrix
I want to practice pixel manipulation with matrix for extract an image from another. This is what I have done with css transformation matrix : https://www.noelshack.com/2017-18-1493893008-capture-2.png With the Left image 'L' I have place 4 points around the image and in the right image 'R' I find the content of the transformation. For that i use the property transform of the css but i want to do the manipulation manually. CSS version : matrix3d(1.5456325781948308,1.6561987730956724,0,0.0012239101773909712,-0.4663849104791486,2.218793881308064,0,0.0009095626603861196,0,0,1,0,12.247969030166722,-17.754955132517754,0,0.9951722722714726) Matrix 'M': [[1.5456325781948308, 1.6561987730956724, 0, 0.0012239101773909712], [-0.4663849104791486, 2.218793881308064, 0, 0.0009095626603861196], [0, 0, 1, 0], [12.247969030166722, -17.754955132517754, 0, 0.9951722722714726]] I want to know for each pixel in the image R what are their pixel related position in the image L. For example (0,0) in R is (52,203) in R. For that i do this calculation. M * P = P' P is the pixel position in R image P' is the pixel position in L image P matrix is define like that: [[x], [y], [0], [1]] So for the 0,0 position, I do this : [[1.5456325781948308, 1.6561987730956724, 0, 0.0012239101773909712], [-0.4663849104791486, 2.218793881308064, 0, 0.0009095626603861196], [0, 0, 1, 0], [12.247969030166722, -17.754955132517754, 0, 0.9951722722714726]] X [[0], [0], [0], [1]] = [[0.0012239101773909712], [0.0009095626603861196], [0], [0.9951722722714726]] This is the result, but the 2 first component : (0.0012239101773909712, 0.0009095626603861196) is too smaller than expected. can you help me to find the problem. scincerly, MatrixCuriosity.
These are homogeneous coordinates. So given some [x1, y1, z1, 1] as input you obtain some [x2, y2, z2, w2] but the actual position they describe is [x2/w2, y2/w2, z2/w2], i.e. you have to divide by the last coordinate. But this doesn't lead to the result you expected. Nor does replacing the matrix with its adjunct (or equivalently inverse), nor its transpose. Both of these are conventions that are easy to get wrong, so without spending too much thought about which version you actually have and should have, trying all four alternatives (with and without adjunct, with and without transpose) solves a huge number of trivial problems. But not yours. So my next best bet would be that the coordinates you expect are measured from some corner of the image, while the CSS property transform-origin is at it's initial value of 50% 50% 0 so the origin of the coordinate system is in fact in the center of the object. Actually sharing the HTML and CSS for this might have allowed me to verify this assumption. Now you have to check whether this applies to you. I remember that when I last created a projective image transformation demo to answer a question about finding the transform, I deliberately set transform-origin: 0 0; (and the various vendor-prefixed versions of this) to avoid such problems.
Thanks a lot MvG. I follow your link and I find what I want [https://math.stackexchange.com/a/339033] Just one thing, I have to invert the C matrix to find the pixel related L<-R I share my code for give an idea of what you have to do You can find my implementation in the function computeMat() <style> body { touch-action: none; overflow-y: hidden; } #canvas_toeic { position:absolute; top:0; left:0; } </style> <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/mathjs/3.12.2/math.min.js"></script> </head> <body> <canvas id="canvas_toeic" width="600" height="400"> </canvas> <script type="text/javascript"> var image = new Image(); image.src = 'image.jpg'; image.onload = function() { var c = document.getElementById("canvas_toeic"); var ratio = image.width / image.height; var canvasWidth = document.body.clientWidth; var canvasHeight = canvasWidth / ratio; if(document.body.clientHeight < canvasHeight) { canvasHeight = document.body.clientHeight; canvasWidth = canvasHeight * ratio; } var canvasLargeur = canvasWidth; var canvasLongueur = canvasHeight; if(canvasLargeur < canvasHeight) { canvasLargeur = canvasHeight; canvasLongueur = canvasWidth; } var canvasPixelRatio = canvasLargeur / image.width; c.setAttribute("width", canvasWidth); c.setAttribute("height", canvasHeight); var ctx = c.getContext("2d"); var idPoint = -1; var points = []; for(var i = 0; i < 4; i++) points[i] = {x:0, y:0}; var marginImage = Math.round(40 * canvasPixelRatio); points[0].x = marginImage; points[0].y = marginImage; points[1].x = marginImage; points[1].y = canvasHeight - marginImage; points[2].x = canvasWidth - marginImage; points[2].y = canvasHeight - marginImage; points[3].x = canvasWidth - marginImage; points[3].y = marginImage; function draw(points) { console.log("draw"); // Fond ctx.fillStyle = "#222"; ctx.fillRect(0, 0, canvasWidth, canvasHeight); ctx.drawImage(image, marginImage, marginImage, canvasWidth - marginImage * 2, canvasHeight - marginImage * 2); // this fait référence à l'objet courant (=image) if(idPoint == -1) ctx.lineWidth = 3 * canvasPixelRatio; else ctx.lineWidth = 5 * canvasPixelRatio; ctx.beginPath(); // Début du chemin ctx.lineJoin = "round"; ctx.lineCap = "round"; ctx.strokeStyle = "rgba(64, 128, 255, 0.5)"; ctx.moveTo(points[0].x, points[0].y); // Le tracé part du point 50,50 for(var i = 0; i < 4; i++) ctx.lineTo(points[i].x, points[i].y); // Un segment est ajouté vers 200,200 ctx.closePath(); // Fermeture du chemin (facultative) ctx.stroke(); for(var i = 0; i < 4; i++) { var radius = 30 * canvasPixelRatio; if(idPoint == i) radius = 60 * canvasPixelRatio; ctx.beginPath(); ctx.arc(points[i].x, points[i].y, radius, 0, Math.PI*2, true); ctx.strokeStyle = "#FF8800"; ctx.fillStyle = "rgba(255, 128, 0, 0.5)"; ctx.fill(); ctx.stroke(); } if(idPoint != -1) { var zoomWidth = canvasWidth / 3; var zoomHeight = canvasHeight / 3; var zoomMargin = 5; var zoomAroundWidth = 50; var zoomAroundHeight = zoomAroundWidth / ratio; var positionMouse = points[idPoint]; var imagePositionX = (positionMouse.x - marginImage) / (canvasWidth - marginImage * 2) * image.width; var imagePositionY = (positionMouse.y - marginImage) / (canvasHeight - marginImage * 2) * image.height; var zoomX = 0; var zoomY = 0; if(imagePositionX < image.width / 2) zoomX = canvasWidth - zoomWidth; if(imagePositionY < image.height / 2) zoomY = canvasHeight - zoomHeight; ctx.fillStyle = "#F08"; ctx.fillRect(zoomX, zoomY, zoomWidth, zoomHeight); ctx.drawImage(image, imagePositionX - zoomAroundWidth, imagePositionY - zoomAroundHeight, zoomAroundWidth * 2, zoomAroundHeight * 2, zoomX + zoomMargin, zoomY + zoomMargin, zoomWidth - zoomMargin * 2, zoomHeight - zoomMargin * 2); ctx.lineWidth = 3 * canvasPixelRatio; ctx.beginPath(); ctx.lineJoin = "round"; ctx.lineCap = "round"; ctx.strokeStyle = "rgba(255, 0, 0, 0.5)"; ctx.moveTo(zoomX, zoomY + zoomHeight / 2); ctx.lineTo(zoomX + zoomWidth, zoomY + zoomHeight / 2); ctx.moveTo(zoomX + zoomWidth / 2, zoomY); ctx.lineTo(zoomX + zoomWidth / 2, zoomY + zoomHeight); ctx.closePath(); ctx.stroke(); } } function nearPoint(points, x, y) { var radiusDetection = 60 * canvasPixelRatio; var distances = []; for(i = 0; i < 4; i++) { var mx = x - points[i].x; var my = y - points[i].y; distances[i] = Math.sqrt(mx * mx + my * my); } minI = 0; minD = distances[0]; for(i = 1; i < 4; i++) { if(minD > distances[i]) { minD = distances[i]; minI = i; } } if(minD <= radiusDetection) return minI; return -1; } function getTouchPosition(e) { var target = null; var mouse = null; if(e.changedTouches != undefined) { var touches = e.changedTouches; mouse = touches[0]; target = touches[0].target; } else if(e.originalTarget != undefined) { mouse = e; target = e.originalTarget; } var coordX = 0; var coordY = 0; if(mouse.layerX != undefined) { coordX = mouse.layerX; coordY = mouse.layerY; } else { coordX = mouse.pageX; coordY = mouse.pageY; } var x = coordX - target.offsetLeft; var y = coordY - target.offsetTop; if(x < 0) x = 0; if(y < 0) y = 0; if(x >= canvasWidth) x = canvasWidth - 1; if(y >= canvasHeight) y = canvasHeight - 1; return {'x':x, 'y':y}; } function mouseDown(e) { var position = getTouchPosition(e); idPoint = nearPoint(points, position.x, position.y); if(idPoint == -1) { if(position.x < marginImage * 3 && position.y < marginImage * 3) { computeMat(); } } } function mouseUp(e) { if(idPoint != -1) { idPoint = -1; draw(points); } } function mouseMove(e) { if(idPoint != -1) { var position = getTouchPosition(e); points[idPoint].x = position.x; points[idPoint].y = position.y; draw(points); } } function cancelDefault(e) { e.preventDefault(); } function matStep12(pts) { var matP = [ [pts[0].x, pts[1].x, pts[2].x], [pts[0].y, pts[1].y, pts[2].y], [1, 1, 1] ]; var vecP = [[pts[3].x], [pts[3].y], [1]]; var matPi = math.inv(matP); var vecPi = math.multiply(matPi, vecP); var result = [ [pts[0].x * vecPi[0][0], pts[1].x * vecPi[1][0], pts[2].x * vecPi[2][0]], [pts[0].y * vecPi[0][0], pts[1].y * vecPi[1][0], pts[2].y * vecPi[2][0]], [vecPi[0][0], vecPi[1][0], vecPi[2][0]] ]; return result; } function distance(a, b) { var mx = b.x - a.x; var my = b.y - a.y; return Math.sqrt(mx * mx + my * my); } function computeMat() { var pts = getPointRelativePosition(); var widthT = distance(pts[0], pts[3]); var widthB = distance(pts[1], pts[2]); var heightL = distance(pts[0], pts[1]); var heightR = distance(pts[2], pts[3]); var maxWidth = (widthT > widthB) ? widthT : widthB; var maxHeight = (heightL > heightR) ? heightL : heightR; var imgWidth = Math.round(maxWidth); var imgHeight = Math.round(maxHeight); var matA = matStep12(pts); var matB = matStep12([{x:0,y:0}, {x:0,y:maxHeight}, {x:maxWidth,y:maxHeight}, {x:maxWidth,y:0}]); var matC = math.multiply(matB, math.inv(matA)); var matCi = math.inv(matC); console.log('width:' + imgWidth + ', height:' + imgHeight); printMat(matC); // construct image with transformation matrice imageData = ctx.createImageData(imgWidth, imgHeight); var tempCanvas = document.createElement('canvas'); var tempCtx = tempCanvas.getContext('2d'); tempCanvas.width = image.width; tempCanvas.height = image.height; tempCtx.drawImage(image, 0, 0, image.width, image.height); var imageDataSrc = tempCtx.getImageData(0, 0, image.width, image.height); var mz = [matCi[0][2], matCi[1][2], matCi[2][2]]; for(var y = 0; y < imgHeight; y++) { var my = [matCi[0][1] * y, matCi[1][1] * y, matCi[2][1] * y]; var offsetY = y * imgWidth; for(var x = 0; x < imgWidth; x++) { var mx = [matCi[0][0] * x, matCi[1][0] * x, matCi[2][0] * x]; var cx = mx[0] + my[0] + mz[0]; var cy = mx[1] + my[1] + mz[1]; var cz = mx[2] + my[2] + mz[2]; var px = Math.round(cx / cz); var py = Math.round(cy / cz); if(px < 0.0 || py < 0.0 || px >= image.width || py >= image.height) { imageData.data[pixelIndex] = 0; imageData.data[pixelIndex + 1] = 255; imageData.data[pixelIndex + 2] = 0; imageData.data[pixelIndex + 3] = 255; } else { var pixelIndex = (offsetY + x) * 4; var pixelIndexSrc = (py * image.width + px) * 4; imageData.data[pixelIndex] = imageDataSrc.data[pixelIndexSrc]; imageData.data[pixelIndex + 1] = imageDataSrc.data[pixelIndexSrc + 1]; imageData.data[pixelIndex + 2] = imageDataSrc.data[pixelIndexSrc + 2]; imageData.data[pixelIndex + 3] = 255; } } } // here to do, image analysis } function getPointRelativePosition() { var pointOrigin = []; for(i = 0; i < 4; i++) { pointOrigin[i] = {x:(points[i].x - marginImage) * image.width / (canvasWidth - marginImage * 2), y:(points[i].y - marginImage) * image.height / (canvasHeight - marginImage * 2)}; } return pointOrigin; } function getPointPosition() { var pointOrigin = []; for(i = 0; i < 4; i++) { pointOrigin[i] = {x:(points[i].x - marginImage) / (canvasWidth - marginImage * 2), y:(points[i].y - marginImage) / (canvasHeight - marginImage * 2)}; } return pointOrigin; } function printPoint(pts) { var result = ''; for(var i = 0; i < 4; i++) { result += "{x:" + pts[i].x + ", y:" + pts[i].y + "},\n"; } console.log(result); } function printMat(mat) { var result = ''; for(var i = 0; i < mat.length; i++) { result += "["; for(var j = 0; j < mat[i].length; j++) { result += mat[i][j] + ", "; } result += "],\n"; } console.log(result); } function canvasResize() { if(canvasWidth != document.body.clientWidth && canvasHeight != document.body.clientHeight) { var transformPoint = getPointPosition(); ratio = image.width / image.height; canvasWidth = document.body.clientWidth; canvasHeight = canvasWidth / ratio; if(document.body.clientHeight < canvasHeight) { canvasHeight = document.body.clientHeight; canvasWidth = canvasHeight * ratio; } canvasLargeur = canvasWidth; canvasLongueur = canvasHeight; if(canvasLargeur < canvasHeight) { canvasLargeur = canvasHeight; canvasLongueur = canvasWidth; } canvasPixelRatio = canvasLargeur / image.width; c.setAttribute("width", canvasWidth); c.setAttribute("height", canvasHeight); marginImage = Math.round(40 * canvasPixelRatio); for(i = 0; i < 4; i++) { points[i].x = transformPoint[i].x * (canvasWidth - marginImage * 2) + marginImage; points[i].y = transformPoint[i].y * (canvasHeight - marginImage * 2) + marginImage; } draw(points); } } c.addEventListener("mousedown", mouseDown, false); c.addEventListener("mouseup", mouseUp, false); c.addEventListener("mousemove", mouseMove, false); c.addEventListener("touchstart", mouseDown, false); c.addEventListener("touchend", mouseUp, false); c.addEventListener("touchmove", mouseMove, false); document.addEventListener("touchstart", cancelDefault, true); document.addEventListener("touchend", cancelDefault, true); document.addEventListener("touchmove", cancelDefault, true); setInterval(canvasResize, 30); draw(points); }; </script>
Swift 2 PhysicsBody not working
i have a code where i two spaceships floating around the screen however they can't break through the top of the screen and the motto. however they can fly through i sides. i've look at endless about of sites and done some many different types of skphysicsbodys but none of them help. code example. class GameScene: SKScene, SKPhysicsContactDelegate { var player = SKSpriteNode(imageNamed: "spaceship.png") var player2 = SKSpriteNode(imageNamed: "spaceship.png") var timer = NSTimer() var tapsValid:Bool? var playerRight:Bool? var playerChange:Bool? override func didMoveToView(view: SKView) { let sceneBody = SKPhysicsBody(edgeLoopFromRect: self.frame) sceneBody.friction = 0 self.physicsBody = sceneBody physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0) tapsValid = true playerRight = true self.scene?.backgroundColor = UIColor.whiteColor() player.position = CGPointMake(self.size.width / 2, self.size.height / 1.8 + 280) player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size) player.physicsBody?.dynamic = false player.physicsBody?.affectedByGravity = false player.physicsBody?.restitution = 1 player.physicsBody?.friction = 0 player.physicsBody?.linearDamping = 0 player.physicsBody?.angularDamping = 0 player2.position = CGPointMake(self.size.width / 2, self.size.height / 14) player2.physicsBody = SKPhysicsBody(rectangleOfSize: player2.size) player2.physicsBody?.affectedByGravity = false player2.physicsBody?.dynamic = false player2.physicsBody?.restitution = 1 player2.physicsBody?.friction = 0 player.physicsBody?.linearDamping = 0 player.physicsBody?.angularDamping = 0 self.addChild(player) self.addChild(player2) can anyone help me out here. i just want to add physics to the edges of the screen. Thanks,
You should define your colliderTypes and categories for your nodes. That way you can check to see what hits what enum ColliderType: UInt32 { case Spaceship = 0 case CornerCategory = 1 } self.physicsBody!.categoryBitMask = ColliderType.CornerCategory.rawValue player.physicsBody?.contactTestBitMask = ColliderType.CornerCategory.rawValue player2.physicsBody?.contactTestBitMask = ColliderType.CornerCategory.rawValue func didBeginContact(contact: SKPhysicsContact) { if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { //If it is true. Means that bodyA is the spaceship. Because it's 0 firstBody = contact.bodyA secondBody = contact.bodyB }else{ //Either way. firstBody will always be the spaceship firstBody = contact.bodyB secondBody = contact.bodyA } if firstBody.categoryBitMask == ColliderType. Spaceship.rawValue && secondBody.categoryBitMask == ColliderType.CornerCategory.rawValue{ //means that Spaceship and wall touches print("Spaceship hits wall") } }
Add NSClickGestureRecognizer to NSButton programmatically swift
I have multiple NSButtons generated with this code: var height = 0 var width = 0 var ar : Array<NSButton> = [] var storage = NSUserDefaults.standardUserDefaults() height = storage.integerForKey("mwHeight") width = storage.integerForKey("mwWidth") var x = 0 var y = 0 var k = 1 for i in 1...height { for j in 1...width { var but = NSButton(frame: NSRect(x: x, y: y + 78, width: 30, height: 30)) but.tag = k but.title = "" but.action = Selector("buttonPressed:") but.target = self but.bezelStyle = NSBezelStyle(rawValue: 6)! ar.append(but) self.view.addSubview(but) x += 30 k++ } y += 30 x = 0 } And I need to add the NSClickGestureRecognizer to each of them to recognize secondary mouse button clicks. Is there any way to do that programmatically?
This should work: let g = NSClickGestureRecognizer() g.target = self g.buttonMask = 0x2 // right button g.numberOfClicksRequired = 1 g.action = Selector("buttonGestured:") but.addGestureRecognizer(g) and later func buttonGestured(g:NSGestureRecognizer) { debugPrintln(g) debugPrintln(g.view) if let v = g.view as? NSButton { debugPrintln("tag: \(v.tag)") } }