Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change center of gravity in sprite kit game?

I have been trying to find, but did not succeed. Is there a way to change physicsworld gravity property in such way, that objects would not be attracted towards the bottom of the screen, but to the centre of it instead?

like image 361
TruniTr Avatar asked Aug 31 '25 17:08

TruniTr


2 Answers

Use an SKFieldNode for that. Just place it at the center of your map and disable gravity by putting code in that sets the gravity to zero (CGVector(0,0))

I would give you code, but I don't use Objective C, so I don't know the exact syntax for it. I can give it a shot though... [physicsBody setGravity: CGVector(0,0)]; PLEASE NOTE I HAVE NO IDEA IF THAT IS CORRECT SYNTAX

EDIT: The asker requested an example of SKFieldNode in Swift, so here it goes. For the question asked, what you would do is create a Radial Gravity Field node at the center. This code goes in GameScene.swift (or .m if you're using Objective C, and make sure you change the syntax to Obj-C).

let gravField = SKFieldNode.radialGravityField(); // Create grav field
gravField.position.x = size.width/2; // Center on X axis
gravField.position.y = size.height/2; // Center on Y axis (Now at center of screen)
addChild(gravField); // Add to world
like image 152
sjbrimhall Avatar answered Sep 02 '25 07:09

sjbrimhall


You are probably looking for a SKFieldNode. There are a couple of different types so you will have to read the docs. The one you are probably looking for is called radialGravityField.

like image 35
sangony Avatar answered Sep 02 '25 09:09

sangony