i have to following code that makes a custom physicsBody for my enemy.
see the code below:
let offsetX = CGFloat(Enemy.frame.size.width * Enemy.anchorPoint.x)
let offsetY = CGFloat(Enemy.frame.size.height * Enemy.anchorPoint.y)
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 25 - offsetX, 73 - offsetY)
CGPathAddLineToPoint(path, nil, 32 - offsetX, 72 - offsetY)
CGPathAddLineToPoint(path, nil, 45 - offsetX, 66 - offsetY)
CGPathAddLineToPoint(path, nil, 47 - offsetX, 63 - offsetY)
CGPathAddLineToPoint(path, nil, 43 - offsetX, 11 - offsetY)
CGPathAddLineToPoint(path, nil, 25 - offsetX, 2 - offsetY)
CGPathAddLineToPoint(path, nil, 11 - offsetX, 15 - offsetY)
CGPathAddLineToPoint(path, nil, 5 - offsetX, 29 - offsetY)
CGPathAddLineToPoint(path, nil, 5 - offsetX, 30 - offsetY)
CGPathAddLineToPoint(path, nil, 3 - offsetX, 44 - offsetY)
CGPathAddLineToPoint(path, nil, 3 - offsetX, 51 - offsetY)
CGPathAddLineToPoint(path, nil, 7 - offsetX, 65 - offsetY)
CGPathAddLineToPoint(path, nil, 9 - offsetX, 67 - offsetY)
CGPathAddLineToPoint(path, nil, 15 - offsetX, 70 - offsetY)
CGPathCloseSubpath(path)
Enemy.physicsBody = SKPhysicsBody(polygonFromPath: path)
when i run this code my physicsBody is half the size of my picture. and sits at the bottom left of the picture. how do i fix this?
i figured it out if you multiply all your values it should work!
see the next line of code:
CGPathAddLineToPoint(path, nil, 11*2 - offsetX, 15*2 - offsetY)
Related
I have this code that is working great except that the only way I can figure out to stop making it spin is to turn up the velocityDecay, which makes the animation the point when a new node is introduced to be quite slow -- and doesn't actually stabilize the animation -- it's always moving slightly.
Here's the relevant parts of the code (or tell me if there are other important components):
```
60 let simulation = d3.forceSimulation()
61 .force('link', d3.forceLink()
62 .id((d) => { return d.index + 1 })
63 .distance(200)
64 .strength(1))
65 .force('charge', d3.forceManyBody())
66 .force('x', d3.forceX())
67 .force('y', d3.forceY())
68 .alphaTarget(1)
69 .on('tick', ticked)
70 .force('center', d3.forceCenter(window.innerWidth/2, window.innerHeight/2))
71 .force('collide', d3.forceCollide( (d) => { return 150 }).iterations(16))
72
73 svg.append('g').attr('class', 'links')
74
75 let link = svg.select('.links')
76 .selectAll('.link')
77 .data(links)
78 .enter().append('path')
79 .attr('class', 'link')
80 .attr('fill', 'transparent')
81 .attr('stroke', 'black')
82 .attr('stroke-width', '10px')
83 .exit()
84 .remove()
107 link = link.data(links)
108 .enter().append('path')
109 .attr('class', (d) => {
110 return 'link link-' + d.source + '-' + d.target
111 })
112 .attr('fill', 'transparent')
113 .attr('stroke', 'black')
114 .attr('stroke-width', '10px')
115 .merge(link)
116 link.exit().remove()
147 simulation.nodes(nodes)
148 .on('tick', ticked)
149 simulation
150 .force('charge', d3.forceManyBody())
151 // .force('center', d3.forceCenter(window.innerWidth/2, window.innerHeight/2))
152 // .force('collide', d3.forceCollide( (d) => { return 150 }).iterations(156))
153 // .alphaTarget(1)
154 .alphaDecay(.5)
155 // .alpha(1)
156 // .velocityDecay(.95)
157 .force('link', d3.forceLink()
158 .id((d) => { return d.index + 1})
159 .distance(200)
160 .iterations(20)
161 .strength(1))
162 .force('x', d3.forceX())
163 .force('y', d3.forceY())
164 .force('link').links(links)
165 simulation.restart()
```
I'm making a macOS app and I've got this code used to rotate an image:
didSet {
let degreesToRotate = oldValue - phoneXRotation
phoneImageView.rotate(byDegrees: CGFloat(degreesToRotate))
degreesLabel.isHidden = false
degreesLabel.stringValue = "\(phoneXRotation)"
if phoneXRotation > 70 {
statusLabel.stringValue = "Phone orientation: Right Tilt"
} else if phoneXRotation < -70 {
statusLabel.stringValue = "Phone orientation: Left Tilt"
} else {
statusLabel.stringValue = "Phone orientation: Flat"
}
}
The app will randomly crash in an lldb error. If I comment out the third line that rotate the phone, I have no problems. The conversion from Int to CGFloat shouldn't crash. Any ideas?
Here is the stack trace:
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
frame #0: 0x00007fff8989b44e AppKit`-[NSApplication _crashOnException:] + 109
frame #1: 0x00007fff8996ea32 AppKit`__37+[NSDisplayCycle currentDisplayCycle]_block_invoke.31 + 708
frame #2: 0x00007fff8ba62d37 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
frame #3: 0x00007fff8ba62ca7 CoreFoundation`__CFRunLoopDoObservers + 391
frame #4: 0x00007fff8ba436d9 CoreFoundation`__CFRunLoopRun + 873
frame #5: 0x00007fff8ba43114 CoreFoundation`CFRunLoopRunSpecific + 420
frame #6: 0x00007fff8afa3ebc HIToolbox`RunCurrentEventLoopInMode + 240
frame #7: 0x00007fff8afa3cf1 HIToolbox`ReceiveNextEventCommon + 432
frame #8: 0x00007fff8afa3b26 HIToolbox`_BlockUntilNextEventMatchingListInModeWithFilter + 71
frame #9: 0x00007fff8953ca54 AppKit`_DPSNextEvent + 1120
frame #10: 0x00007fff89cb87ee AppKit`-[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 2796
frame #11: 0x00007fff895313db AppKit`-[NSApplication run] + 926
frame #12: 0x00007fff894fbe0e AppKit`NSApplicationMain + 1237
* frame #13: 0x000000010000691d Dataspeed Mac Project`main at AppDelegate.swift:12
frame #14: 0x00007fffa11f1235 libdyld.dylib`start + 1
frame #15: 0x00007fffa11f1235 libdyld.dylib`start + 1
I'm working on a menubar application and I've made a custom (borderless) NSWindow which I've added programmatically. For some reason when I try to resize the window, it freezes and I'm unable to resize the window and open the menu-bar menu. However I can still move the window but not click things in it. The weird thing is that there is no error message at all, even though I turned on breakpoints and NSZombieMode. So I've no idea what the problem could be.
// customWindow.m
- (id)initWithContentRect:(NSRect)contentRect
styleMask:(NSUInteger)aStyle
backing:(NSBackingStoreType)bufferingType
defer:(BOOL)flag {
// Using NSBorderlessWindowMask results in a window without a title bar.
self = [super initWithContentRect:contentRect styleMask:NSBorderlessWindowMask | NSResizableWindowMask backing:NSBackingStoreBuffered defer:NO];
if (self != nil) {
if (![[SharedClass sharedManager] lastColor]) {
[self setBackgroundColor:[NSColor colorWithRed:(float)252/255 green:(float)249/255 blue:(float)151/255 alpha:1]];
[[SharedClass sharedManager] setLastColor:self.backgroundColor];
} else {
[self setBackgroundColor: [[SharedClass sharedManager] lastColor]];
}
[self setLevel:NSNormalWindowLevel];
// Start with no transparency for all drawing into the window
// Turn off opacity so that the parts of the window that are not drawn into are transparent.
[self setOpaque:NO];
// [self setBackgroundColor:[NSColor clearColor]];
[self setHasShadow:YES];
[self setMovableByWindowBackground:YES];
[self makeKeyAndOrderFront:theTextView];
panel = [NSColorPanel sharedColorPanel];
[panel setTarget:self];
[panel setColor:self.backgroundColor];
[panel setAction:#selector(colorUpdate:)];
[panel setShowsAlpha:YES];
[self setDelegate:self];
NSRect cFrame = [self frame];
NSView *theView = [[NSView alloc] initWithFrame:cFrame];
[self setContentView:theView];
[self setMinSize:CGSizeMake(100, 100)];
}
return self;
}
- (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)frameSize {
exit.frame = NSMakeRect(2,(frameSize.height-12), 10, 10);
palette.frame = NSMakeRect((frameSize.width-24),(frameSize.height-12), 10, 10);
locker.frame = NSMakeRect((frameSize.width-12),(frameSize.height-12), 10, 10);
theTextView.frame = NSRectFromCGRect(CGRectMake(0, 8, frameSize.width, (frameSize.height-20)));
return frameSize;
}
- (void)windowDidResize:(NSNotification *)notification{
NSLog(#"resized");
}
Stack trace :
0 DDHotKey 0x00000001000044ed -[CustomWindow windowDidResize:] + 61
1 CoreFoundation 0x00007fff9034245c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
2 CoreFoundation 0x00007fff90232634 _CFXNotificationPost + 3140
3 Foundation 0x00007fff8d7f59d1 -[NSNotificationCenter postNotificationName:object:userInfo:] + 66
4 AppKit 0x00007fff89117770 -[NSWindow _setFrameCommon:display:stashSize:] + 2885
5 AppKit 0x00007fff891d4b73 -[NSWindow setFrame:display:animate:] + 641
6 DDHotKey 0x000000010000a8c0 -[DDHotKeyAppDelegate setFrame:animated:] + 416
7 DDHotKey 0x00000001000091ae __53-[DDHotKeyAppDelegate applicationDidFinishLaunching:]_block_invoke + 2318
8 AppKit 0x00007fff895e5233 GlobalObserverHandler + 117
9 HIToolbox 0x00007fff88d0ab6c _ZL23DispatchEventToHandlersP14EventTargetRecP14OpaqueEventRefP14HandlerCallRec + 1260
10 HIToolbox 0x00007fff88d09fae _ZL30SendEventToEventTargetInternalP14OpaqueEventRefP20OpaqueEventTargetRefP14HandlerCallRec + 386
11 HIToolbox 0x00007fff88d09e22 SendEventToEventTargetWithOptions + 43
12 HIToolbox 0x00007fff88d46a9e _ZL29ToolboxEventDispatcherHandlerP25OpaqueEventHandlerCallRefP14OpaqueEventRefPv + 1762
13 HIToolbox 0x00007fff88d0b295 _ZL23DispatchEventToHandlersP14EventTargetRecP14OpaqueEventRefP14HandlerCallRec + 3093
14 HIToolbox 0x00007fff88d09fae _ZL30SendEventToEventTargetInternalP14OpaqueEventRefP20OpaqueEventTargetRefP14HandlerCallRec + 386
15 HIToolbox 0x00007fff88d1fcb6 SendEventToEventTarget + 40
16 AppKit 0x00007fff890d71a2 _DPSNextEvent + 3001
17 AppKit 0x00007fff890d5f68 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 346
18 AppKit 0x00007fff890cbbf3 -[NSApplication run] + 594
19 AppKit 0x00007fff89048354 NSApplicationMain + 1832
20 DDHotKey 0x0000000100007312 main + 34
21 libdyld.dylib 0x00007fff8bd335c9 start + 1
The score component of the game was operating normally, but recently I've implemented GameKit and it is adding more to the score than what is in the code.
else if key == kCollectableStarKey {
sprite = Collectable(texture: atlas.textureNamed("StarGold"))
(sprite as! Collectable).collectionSound = Sound(named: "Collect.caf")
(sprite as! Collectable).pointValue = 3
(sprite as! Collectable).delegate = self.delegate
sprite.physicsBody = SKPhysicsBody(circleOfRadius: sprite.size.width * 0.3)
sprite.physicsBody?.categoryBitMask = kCollectableCategory
sprite.physicsBody?.dynamic = false
self.addChild(sprite)
}
else if key == kBoneKey {
sprite = Collectable(texture: atlas.textureNamed("FishBone"))
(sprite as! Collectable).collectionSound = Sound(named: "fail.caf")
(sprite as! Collectable).pointValue = -2
(sprite as! Collectable).delegate = self.delegate
sprite.physicsBody = SKPhysicsBody(circleOfRadius: sprite.size.width * 0.3)
sprite.physicsBody?.categoryBitMask = kCollectableCategory
sprite.physicsBody?.dynamic = false
self.addChild(sprite)
}
Here is the Collectable protocol
protocol CollectableDelegate {
func wasCollected(collectable: Collectable)
}
class Collectable: SKSpriteNode {
var delegate: CollectableDelegate!
var collectionSound: Sound!
var pointValue: Int = 0
func collect() {
self.collectionSound.play()
self.runAction(SKAction.removeFromParent())
if let delegate = self.delegate {
self.delegate.wasCollected(self)
}
}
}
and the Bone Protocol:
protocol BoneDelegate {
func wasGathered(collectable: boneCollectable)
}
class boneCollectable: SKSpriteNode {
var delegate: BoneDelegate!
var gatherSound: Sound!
var boneValue: Int = 0
func gather() {
self.gatherSound.play()
self.runAction(SKAction.removeFromParent())
if let delegate = self.delegate {
self.delegate.wasGathered(self)
}
}
}
I've uploaded a video of the problem as well:
Video here
So it appears that the problem was with the physics body for my main sprite.
// Setup physics body with path.
let offsetX = self.frame.size.width * self.anchorPoint.x;
let offsetY = self.frame.size.height * self.anchorPoint.y;
var planeBodyPath = CGPathCreateMutable();
CGPathMoveToPoint(planeBodyPath, nil, 19 - offsetX, 0 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 40 - offsetX, 50 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 14 - offsetX, 40 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 38 - offsetX, 11 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 11 - offsetX, 20 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 5 - offsetX, 20 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 36 - offsetX, 28 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 20 - offsetX, 27 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 20 - offsetX, 7 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 54 - offsetX, 13 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 70 - offsetX, 31 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 70 - offsetX, 40 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 69 - offsetX, 55 - offsetY);
CGPathCloseSubpath(planeBodyPath);
self.physicsBody = SKPhysicsBody(polygonFromPath: planeBodyPath)
After deleting this and adding this:
// Setup physics body with path.
let offsetX = self.frame.size.width * self.anchorPoint.x;
let offsetY = self.frame.size.height * self.anchorPoint.y;
var planeBodyPath = CGPathCreateMutable();
CGPathMoveToPoint(planeBodyPath, nil, 64 - offsetX, 11 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 77 - offsetX, 42 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 75 - offsetX, 10 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 38 - offsetX, 30 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 11 - offsetX, 54 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 5 - offsetX, 57 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 36 - offsetX, 61 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 76 - offsetX, 27 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 74 - offsetX, 7 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 54 - offsetX, 13 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 14 - offsetX, 31 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 27 - offsetX, 62 - offsetY);
CGPathAddLineToPoint(planeBodyPath, nil, 69 - offsetX, 55 - offsetY);
CGPathCloseSubpath(planeBodyPath);
self.physicsBody = SKPhysicsBody(polygonFromPath: planeBodyPath)
All worked normally with the scoring system. I have no clue as to why it causes the error however.
So I have a labeled array (array1) with connected regions of interest (background is all zeros, connected regions are all 1's for the first region, all 2's for the second, 3's for the 3rd etc.) I also have a vector (vector1) of the region labels I find important (ex. 1,6,9). I want to find the locations of these values in the labeled array and then change values in one channel of a separate 3 channel array at the same locations (want to color certain parts of an image green based regions of interest found in another image).
I can use the below code to change all channels, but don't know how to specify (img(y,x,1=0), img(y,x,2=0), img(y,x,3=255)).
for i=1:1:length(vector1)
img(array1==vector1(i))=255;
end
If I understand you correctly, you have a label map of objects - each with an associated ID with 0 as the background. You also have a vector of important IDs and a colour image that is associated with this label map.
You wish to set all locations that have an important ID to 1 colour. I would first create a logical mask where true means that the pixel is important and false otherwise. What I mean by important is that the pixel is either 1, 6 or 9 if we go with your example. You can use bsxfun combined with any to create this mask, then we can use this to index into your image and set the right colour to these locations.
Therefore, do this:
%// Create your logical mask
mask3D = bsxfun(#eq, array1, permute(vector(:), [3 2 1]));
mask = any(mask3D, 3);
%// Set the image pixels to blue at these locations
red = img(:,:,1);
green = img(:,:,2);
blue = img(:,:,3);
red(mask) = 0;
green(mask) = 0;
blue(mask) = 255;
img = cat(3, red, green, blue);
Here's a quick example run. Suppose we have this image with squares:
We can see that there are three squares. Let's change object 1 and object 3 to blue. Before we do that, we need to get a label map:
%// Originally a binary image
im = imread('http://i.stack.imgur.com/DnYQS.png');
%// Get label map
array1 = bwlabel(im);
%// Create colour version out of this binary image
img = 255*uint8(im);
img = cat(3, img, img, img);
array1 is our label map as you have also mentioned in your question and img is the colour version of the input image. Now, vector = [1 3] so we can change those objects. The labelling is such that the top left square is label 1, the middle is label 2 and the bottom right is label 3.
Once I do this and I run the above code, this is the image I get:
You can achieve it in two lines -
%// Create a 3D mask to select the labels [1,6,9] only, as listed in "vector1"
mask = bsxfun(#and,ismember(array1,vector1),ones(1,1,3));
%// Map "img" with "mask" and set them to tuple:[0,0,255] (blue color)
img(mask) = reshape(repmat([0 0 255],nnz(mask)/3,1),[],1)
Sample run -
array1 = %// Input
2 0 1 1 0 6
0 0 1 0 0 6
9 0 0 0 0 6
9 9 0 4 0 0
vector1 = %// Input
1 6 9
img(:,:,1) = %// Input: Before code run
228 19 175 30 192 188
204 23 34 164 149 248
188 204 185 84 189 222
14 241 29 167 60 22
img(:,:,2) =
94 202 197 59 200 136
95 94 53 164 26 24
175 53 100 124 75 104
153 23 141 39 61 27
img(:,:,3) =
29 246 111 48 197 172
201 111 168 68 101 110
75 178 28 204 70 116
154 194 239 125 10 156
img(:,:,1) = %// Output: After code run
228 19 0 0 192 0
204 23 0 164 149 0
0 204 185 84 189 0
0 0 29 167 60 22
img(:,:,2) =
94 202 0 0 200 0
95 94 0 164 26 0
0 53 100 124 75 0
0 0 141 39 61 27
img(:,:,3) =
29 246 255 255 197 255
201 111 255 68 101 255
255 178 28 204 70 255
255 255 239 125 10 156
Notice the positions of the values [1,6,9] in array1 and the corresponding value changes in img1 before and after code runs.