Bouncing ball slightly leaves the screen frame in Spritekit [duplicate] - objective-c

I've been racking my brain and searching here and all over to try to find out how to generate a random position on screen to spawn a circle. I'm hoping someone here can help me because I'm completely stumped. Basically, I'm trying to create a shape that always spawns in a random spot on screen when the user touches.
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenHeight = screenSize.height
let screenWidth = screenSize.width
let currentBall = SKShapeNode(circleOfRadius: 100)
currentBall.position = CGPointMake(CGFloat(arc4random_uniform(UInt32(Float(screenWidth)))), CGFloat(arc4random_uniform(UInt32(Float(screenHeight)))))
self.removeAllChildren()
self.addChild(currentBall)
}
If you all need more of my code, there really isn't any more. But thank you for whatever help you can give! (Just to reiterate, this code kind of works... But a majority of the spawned balls seem to spawn offscreen)

The problem there is that you scene is bigger than your screen bounds
let viewMidX = view!.bounds.midX
let viewMidY = view!.bounds.midY
print(viewMidX)
print(viewMidY)
let sceneHeight = view!.scene!.frame.height
let sceneWidth = view!.scene!.frame.width
print(sceneWidth)
print(sceneHeight)
let currentBall = SKShapeNode(circleOfRadius: 100)
currentBall.fillColor = .green
let x = view!.scene!.frame.midX - viewMidX + CGFloat(arc4random_uniform(UInt32(viewMidX*2)))
let y = view!.scene!.frame.midY - viewMidY + CGFloat(arc4random_uniform(UInt32(viewMidY*2)))
print(x)
print(y)
currentBall.position = CGPoint(x: x, y: y)
view?.scene?.addChild(currentBall)
self.removeAllChildren()
self.addChild(currentBall)

First: Determine the area that will be valid. It might not be the frame of the superview because perhaps the ball (let's call it ballView) might be cut off. The area will likely be (in pseudocode):
CGSize( Width of the superview - width of ballView , Height of the superview - height of ballView)
Once you have a view of that size, just place it on screen with the origin 0, 0.
Secondly: Now you have a range of valid coordinates. Just use a random function (like the one you are using) to select one of them.
Create a swift file with the following:
extension Int
{
static func random(range: Range<Int>) -> Int
{
var offset = 0
if range.startIndex < 0 // allow negative ranges
{
offset = abs(range.startIndex)
}
let mini = UInt32(range.startIndex + offset)
let maxi = UInt32(range.endIndex + offset)
return Int(mini + arc4random_uniform(maxi - mini)) - offset
}
}
And now you can specify a random number as follows:
Int.random(1...1000) //generate a random number integer somewhere from 1 to 1000.
You can generate the values for the x and y coordinates now using this function.

Given the following random generators:
public extension CGFloat {
public static var random: CGFloat { return CGFloat(arc4random()) / CGFloat(UInt32.max) }
public static func random(between x: CGFloat, and y: CGFloat) -> CGFloat {
let (start, end) = x < y ? (x, y) : (y, x)
return start + CGFloat.random * (end - start)
}
}
public extension CGRect {
public var randomPoint: CGPoint {
var point = CGPoint()
point.x = CGFloat.random(between: origin.x, and: origin.x + width)
point.y = CGFloat.random(between: origin.y, and: origin.y + height)
return point
}
}
You can paste the following into a playground:
import XCPlayground
import SpriteKit
let view = SKView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
XCPShowView("game", view)
let scene = SKScene(size: view.frame.size)
view.presentScene(scene)
let wait = SKAction.waitForDuration(0.5)
let popIn = SKAction.scaleTo(1, duration: 0.25)
let popOut = SKAction.scaleTo(0, duration: 0.25)
let remove = SKAction.removeFromParent()
let popInAndOut = SKAction.sequence([popIn, wait, popOut, remove])
let addBall = SKAction.runBlock { [unowned scene] in
let ballRadius: CGFloat = 25
let ball = SKShapeNode(circleOfRadius: ballRadius)
var popInArea = scene.frame
popInArea.inset(dx: ballRadius, dy: ballRadius)
ball.position = popInArea.randomPoint
ball.xScale = 0
ball.yScale = 0
ball.runAction(popInAndOut)
scene.addChild(ball)
}
scene.runAction(SKAction.repeatActionForever(SKAction.sequence([addBall, wait])))
(Just make sure to also paste in the random generators, too, or to copy them to the playground's Sources, as well as to open the assistant editor so you can see the animation.)

Related

How to Focus last cell of visible cell of collection view?

I want to focus and change the frame of last cell of visible cell of collectionView.
I want collection view behaviour like this.
I found the library that change the first cell of collection view but I want to change the frame of last cell. This library using flow layout.
override func prepareLayout() {
cache.removeAll(keepCapacity: false)
let standardHeight = UltravisualLayoutConstants.Cell.standardHeight
let featuredHeight = UltravisualLayoutConstants.Cell.featuredHeight
var frame = CGRectZero
var y: CGFloat = 0
for item in 0..<numberOfItems {
// 1
let indexPath = NSIndexPath(forItem: item, inSection: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
// 2
attributes.zIndex = item
var height = standardHeight
// 3
if indexPath.item == featuredItemIndex
{
// 4
let yOffset = standardHeight * nextItemPercentageOffset
y = collectionView!.contentOffset.y - yOffset
height = featuredHeight
} else if indexPath.item == (featuredItemIndex + 1) && indexPath.item != numberOfItems {
// 5
let maxY = y + standardHeight
height = standardHeight + max((featuredHeight - standardHeight) * nextItemPercentageOffset, 0)
y = maxY - height
}
// 6
frame = CGRect(x: 0, y: y, width: width, height: height)
//print("Item : \(item) : \(frame)");
attributes.frame = frame
cache.append(attributes)
y = CGRectGetMaxY(frame)
}
}
library uses above function to change the frame of all elements.
Can any one tell me that how can I achieve this.
You can use visible cells of a UICollectionView to get the array of visible cells and focus on the lastObject of the array

While Loop and rotations. Is there a way to keep it within in the boundaries?

I am using a while loop, rotate and translate in order to get the effect I want for my program. I want to be able to contain the loop within the boundaries of the sketch. Can anyone explain to me how that can be done, please?
Here is the code:
float x, y, r, g, b, radius;
void setup()
{
size(800, 700);
smooth();
frameRate(15);
}
void draw()
{
handleRedBox();
}
void handleRedBox() {
background(255);
stroke(255, 0, 0);
color from = color(100, random(255), 2);
color to = color(0, 200, 0);
color interA = lerpColor (to, from, .44);
int x = 100;
while (x < width/2 || x> width/2 ) {
int y = 100;
while (y <height/2 || y > height/2) {
blendMode(DIFFERENCE);
noStroke();
fill(interA);
quadstuff();
strokeWeight(5);
stroke(0, random(255), 0);
line(width/2, height/2, mouseY, mouseX);
translate(width, height);
rotate(radians(frameCount));
y = y + 50;
}
x = x + 50;
}
ghostcirc();
ghostcirc2();
}
void ghostcirc() {
int w = 0;
while (w < width) {
int q = 0;
while (q <height) {
blendMode(ADD);
fill(random(61), random(90), random(250));
ellipse(255, 255, 100, 100);
;
noStroke();
translate(width, height);
rotate(radians(frameCount));
q = q + 100;
}
w = w + 50;
}
}
void ghostcirc2() {
for (int w= 0; w < width; w+=10) {
blendMode(ADD);
fill(random(61), random(90), random(250));
ellipse(50, 50, 75, 75);
;
noStroke();
translate(width, height);
rotate(radians(frameCount));
//if (keyPressed == true){
// fill(random(100), random(90), random(250));
}
}
void quadstuff() {
int rad = 60; // Width of the shape
float xpos, ypos; // Starting position of shape
float xspeed = 2.8; // Speed of the shape
float yspeed = 2.2; // Speed of the shape
xpos = width/2;
ypos = height/2;
//ellipse(mouseX+x, mouseY+y, 100,100);
quad(xpos, ypos, rad, rad, mouseX+rad, mouseY+rad, xspeed, yspeed);
stroke(0);
strokeWeight(5);
}
Your question is still pretty broad, and that's still a lot of code to try to debug. But I appreciate that you went through the trouble of narrowing it down, so I'm going to try to help in general terms.
Your code involves a lot of stuff that I don't really understand, so I'm going to start with a simpler example. Honestly you might be better off doing the same- start over with something more basic, and add the bounding logic from the beginning. That's going to be much easier than trying to add it in after you've already written everything.
So, there are two main ways to do this type of animation in Processing. I'll cover both.
Option 1: Rely on translate() and rotate() to position stuff for you.
This is what your code does. Here is a simpler example that shows an ellipse rotating around the mouse position:
float angle = 0;
void setup() {
size(500, 500);
}
void draw() {
angle+=.1;
background(0);
translate(mouseX, mouseY);
rotate(angle);
translate(100, 0);
ellipse(0, 0, 50, 50);
}
Now, if you want to bound the ellipse to stay inside the window, first you need to determine where the ellipse will be on the screen. This could be complicated since we're using the translate() and rotate() functions, which are a little like moving the camera instead of moving the ellipse- the ellipse "thinks" it's still at position 0,0. So we need to get the position of the ellipse after we move the camera. Luckily Processing gives us the screenX() and screenY() functions:
float screenX = screenX(0, 0);
float screenY = screenY(0, 0);
This will tell us where on the screen the ellipse will be drawn (or more accurately, where position 0,0 will be after the transforms are applied). We can use this to check whether these go outside the bounds of the window, and then do whatever bounding you want.
Exactly what type of bounding you do depends on what you want to happen. You could wrap the animation around the screen so that when it goes off the right side it reappears on the left side. You could limit the positions so they only go to the border of the window instead of moving past it. Here is that:
float angle = 0;
void setup() {
size(500, 500);
}
void draw() {
angle+=.1;
background(0);
translate(mouseX, mouseY);
rotate(angle);
translate(100, 0);
float screenX = screenX(0, 0);
float screenY = screenY(0, 0);
if (screenX < 25) {
rotate(-angle);
translate(25-screenX, 0);
rotate(angle);
} else if (screenX > 475) {
rotate(-angle);
translate(475-screenX, 0);
rotate(angle);
}
if (screenY < 25) {
rotate(-angle);
translate(0, 25-screenY);
rotate(angle);
} else if (screenY > 475) {
rotate(-angle);
translate(0, 475-screenY);
rotate(angle);
}
ellipse(0, 0, 50, 50);
}
This code is the same as above, except now it uses screenX() and screenY() to determine when the ellipse will be off the screen, and then uses translate() to move it back inside the bounds of the screen.
Option 2: Keep track of the position yourself.
Instead of relying on translate() and rotate() to do the positioning for you, you could also just use some basic algebra and trig to do the positioning yourself.
Here is the simple program, without bounding yet:
float angle = 0;
void setup() {
size(500, 500);
}
void draw() {
angle+=.1;
background(0);
float circleX = mouseX + cos(angle)*100;
float circleY = mouseY + sin(angle)*100;
ellipse(circleX, circleY, 50, 50);
}
Notice that I'm calculating the position of the ellipse myself instead of relying on translate() and rotate(). Now it might be easier to think about exactly where the circle will be, so I can do the bounding:
float angle = 0;
void setup() {
size(500, 500);
}
void draw() {
angle+=.1;
background(0);
float circleX = mouseX + cos(angle)*100;
float circleY = mouseY + sin(angle)*100;
if (circleX < 25) {
circleX = 25;
} else if (circleX > 475) {
circleX = 475;
}
if (circleY < 25) {
circleY = 25;
} else if (circleY > 475) {
circleY = 475;
}
ellipse(circleX, circleY, 50, 50);
}
This might be a little easier to think about, since you can work with the screen coordinates directly. Both options do the same thing, they're just different ways of thinking about it.
From here it's just a matter of defining exactly how your bounding should work. I've given you one example, but you could do anything you want.
You might also want to restrict your input variables (in my case, mouseX and mouseY) so the animation never leaves the window. Adding this at the top of the draw() function of either one of the above options will prevent the animation from leaving the screen:
if (mouseX < 150) {
mouseX = 150;
} else if (mouseX > 350) {
mouseX = 350;
}
if (mouseY < 150) {
mouseY = 150;
} else if (mouseY > 350) {
mouseY = 350;
}
Again, how you do this is really up to you and what you want to happen. It will probably be easier if you start over with a basic program like mine and then add one small thing at a time instead of trying to add it to your existing huge sketch. Good luck.

Famo.us physics engine: forces and walls not behaving as expected

I am tyring to create a grid of particles, using the famous physics engine. I thought that if 25 particles were placed beteween 4 bounding walls (forming a square) and they all had an equal repulsion force to each other, they would naturally form a grid - ie. they would all be held as far away from each other as possible, given the limits of their world. I expected this to work, even if the particles were just added without an initial position. However, even if I give them an initial position, they don't hold in place unless the force is very small.
Also, I thought that if a wall had a restitution of 0, then a particle would just stop on colliding with it. When I run the code below, I can see particles bouncing off walls. The pen is at:
http://codepen.io/timsig/pen/pJJrOa
What am I failing to grasp? - thanks in advance
define('main', function (require, exports, module) {
// import dependencies
var Engine = require('famous/core/Engine');
var Surface = require('famous/core/Surface')
var Modifier = require('famous/core/Modifier');
var PhysicsEngine = require('famous/physics/PhysicsEngine');
var Particle = require('famous/physics/bodies/Particle');
var Drag = require('famous/physics/forces/Drag');
var RepulsionForce = require('famous/physics/forces/Repulsion');
var Wall = require('famous/physics/constraints/Wall');
var gridItems = [];
var positionsArray = [-140,-70,0,70,140];
var context = Engine.createContext();
var physics = new PhysicsEngine();
var gridR = new RepulsionForce({
strength: 0.015
});
//physics.addBody(planetParticle);
var leftWall = new Wall({normal : [1,0,0], distance : 140, restitution : 0});
var rightWall = new Wall({normal : [-1,0,0], distance : 140, restitution : 0});
var topWall = new Wall({normal : [0,1,0], distance : 140, restitution : 0});
var bottomWall = new Wall({normal : [0,-1,0], distance : 140, restitution : 0});
function gridItemTrans() {
return this.particle.getTransform();
}
function addGridRepulsion(){
var sq1, sq2;
for (var i = 0; i < gridItems.length; i += 1){
sq1 = gridItems[i].particle;
physics.attach([leftWall, rightWall, topWall, bottomWall], sq1);
if ((i + 1) < gridItems.length){
for (var j = i + 1; j < gridItems.length; j += 1){
sq2 = gridItems[j].particle;
physics.attach(gridR, sq1, sq2);
}
}
}
}
function addBodies(){
gridItems.forEach(function(ele){
physics.addBody(ele.particle);
});
}
for (var rows = 0; rows < 5; rows += 1){
for (var cols = 0; cols < 5; cols += 1){
var gridItem = new Surface({
properties: {
backgroundColor: '#23AD23'
}
});
gridItem.particle = new Particle({
position: [positionsArray[rows], positionsArray[cols], 0]
});
//physics.addBody(gridItem.particle);
//physics.attach(centralG, gridItemParticle[rows][cols], planetParticle);
gridItem.modifier = new Modifier({
size: [50,50],
align: [0.5, 0.5],
origin: [0.5, 0.5],
transform: gridItemTrans.bind(gridItem)
});
context.add(gridItem.modifier).add(gridItem);
gridItems.push(gridItem);
}
}
addBodies();
addGridRepulsion();
});
To clear up your understanding, we will fist look at the repulsion being applied.
By Default, the Repulsion decay function in Famo.us is a gravity function (an inverse squared distance decay function). Gravity has a decay based on mass and distance.
var gridR = new RepulsionForce({
strength: 1,
decayFunction : RepulsionForce.DECAY_FUNCTIONS.GRAVITY
});
You can apply a linear function to your repulsion decay and you will create the affect you are looking for.
var gridR = new RepulsionForce({
strength: 1,
decayFunction : RepulsionForce.DECAY_FUNCTIONS.LINEAR
});
If gravity were to decay linearly rather than quadratically, you would need infinite kinetic energy to escape a gravitational field. It would be like living in 2D space.
To answer the second part of your question: The walls have no restitution, but the particles still respond to the force of the other particles.

'Grenade' projection based on angle + bounce

I'm having some trouble with synthesizing an advanced object projection formula. I have already figured out few basic physic simulation formulas such as:
Velocity of object:
x += cos(angle);
y += sin(angle);
*where angle can be obtained by either mouse position or with tan(...target and intial values)
but that only travels straight based on the angle.
Gravity:
Yvelocity = Yvelocity - gravity;
if(!isHitPlatform) {
Obj.y += YVelocity
}
Bounce:// No point if we've not been sized...
if (height > 0) {
// Are we bouncing...
if (bounce) {
// Add the vDelta to the yPos
// vDelta may be postive or negative, allowing
// for both up and down movement...
yPos += vDelta;
// Add the gravity to the vDelta, this will slow down
// the upward movement and speed up the downward movement...
// You may wish to place a max speed to this
vDelta += gDelta;
// If the sprite is not on the ground...
if (yPos + SPRITE_HEIGHT >= height) {
// Seat the sprite on the ground
yPos = height - SPRITE_HEIGHT;
// If the re-bound delta is 0 or more then we've stopped
// bouncing...
if (rbDelta >= 0) {
// Stop bouncing...
bounce = false;
} else {
// Add the re-bound degregation delta to the re-bound delta
rbDelta += rbDegDelta;
// Set the vDelta...
vDelta = rbDelta;
}
}
}
}
I need help way to combine these three formulas to create an efficient and lightweight algorithm that allows an object to be projected in an arch determined by the angle, yet continues to bounce a few times before coming to a stop, all with an acceptable amount of discontinuity between each point. *Note: Having the grenade be determined by a f(x) = -x^2 formula creates a larger jump discontinuity as the slope increases, forcing you to reverse the formula to find x = +-y value (to determine whether + or -, check the bounds).
something like:
class granade
{
private static final double dt = 0.1; // or similar
private double speedx;
private double speedy;
private double positionx;
private double positiony;
public granade(double v, double angle)
{
speedx = v * Math.cos(angle);
speedy = v * Math.sin(angle);
positionx = 0;
positiony = 0;
}
public void nextframe()
{
// update speed: v += a*dt
speedy -= gravity* dt;
// update position: pos += v*dt
positionx += speedx * dt;
double newpositiony = positiony + speedy*dt;
// bounce if hit ground
if (newpositiony > 0)
positiony = newpositiony;
else {
// bounce vertically
speedy *= -1;
positiony = -newpositiony;
}
}
public void draw() { /* TODO */ }
}
OT: avoid Math.atan(y/x), use Math.atan2(y, x)

How to find the Joint coordinates(X,Y,Z) ,also how to draw a locus of the tracked joint?

I am trying to develop a logic to recognize a circle which is made by users right hand, I got the code to draw the skeleton and track from the sample code,
private void SensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
{
Skeleton[] skeletons = new Skeleton[0];
using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
{
if (skeletonFrame != null)
{
skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
skeletonFrame.CopySkeletonDataTo(skeletons);
}
}
using (DrawingContext dc = this.drawingGroup.Open())
{
// Draw a transparent background to set the render size
dc.DrawRectangle(Brushes.Black, null, new Rect(0.0, 0.0, RenderWidth, RenderHeight));
if (skeletons.Length != 0)
{
foreach (Skeleton skel in skeletons)
{
RenderClippedEdges(skel, dc);
if (skel.TrackingState == SkeletonTrackingState.Tracked)
{
this.DrawBonesAndJoints(skel, dc);
}
else if (skel.TrackingState == SkeletonTrackingState.PositionOnly)
{
dc.DrawEllipse(
this.centerPointBrush,
null,
this.SkeletonPointToScreen(skel.Position),
BodyCenterThickness,
BodyCenterThickness);
}
}
}
// prevent drawing outside of our render area
this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, RenderWidth, RenderHeight));
}
}
What I want to do now is to track the coordinates of users right hand for gesture recognition,
Here is how I am planning to get the job done:
Start the gesture
Draw the circled gesture, Make sure to store the coordinates for start and then keep noting the coordinates for every 45 degree shift of the Joint from the start, for 8 octants we will get 8 samples.
For making a decision that a circle was drawn we can just check the relation ship between the eight samples.
Also, in the depthimage I want to show the locus of the drawn gesture, so as the handpoint moves it leaves a trace behind so at the end we will get a figure which was drawn by an user. I have no idea how to achieve this.
Coordinates for each joint are available for each tracked skeleton during each SkeletonFrameReady event. Inside your foreach loop...
foreach (Skeleton skeleton in skeletons) {
// get the joint
Joint rightHand = skeleton.Joints[JointType.HandRight];
// get the individual points of the right hand
double rightX = rightHand.Position.X;
double rightY = rightHand.Position.Y;
double rightZ = rightHand.Position.Z;
}
You can look at the JointType enum to pull out any of the joints and work with the individual coordinates.
To draw your gesture trail you can use the DrawContext you have in your example or use another way to draw a Path onto the visual layer. With your x/y/z values, you would need to scale them to the window coordinates. The "Coding4Fun" library offers a pre-built function to do it; alternatively you can write your own, for example:
private static double ScaleY(Joint joint)
{
double y = ((SystemParameters.PrimaryScreenHeight / 0.4) * -joint.Position.Y) + (SystemParameters.PrimaryScreenHeight / 2);
return y;
}
private static void ScaleXY(Joint shoulderCenter, bool rightHand, Joint joint, out int scaledX, out int scaledY)
{
double screenWidth = SystemParameters.PrimaryScreenWidth;
double x = 0;
double y = ScaleY(joint);
// if rightHand then place shouldCenter on left of screen
// else place shouldCenter on right of screen
if (rightHand)
{
x = (joint.Position.X - shoulderCenter.Position.X) * screenWidth * 2;
}
else
{
x = screenWidth - ((shoulderCenter.Position.X - joint.Position.X) * (screenWidth * 2));
}
if (x < 0)
{
x = 0;
}
else if (x > screenWidth - 5)
{
x = screenWidth - 5;
}
if (y < 0)
{
y = 0;
}
scaledX = (int)x;
scaledY = (int)y;
}