How to have a character moved around the screen? - iphone

I already have a joystick programmed (finally) and I was wondering how I would get a 'hero' to move about the screen based on where the joystick is? I am using Cocos2d and any help would be greatly appreciated!

The simplest way to do this is to subclass CCNode for your player object and then manipulate it as you would any other CCNode. To start with, you can change the player's position struct like so:
player.position = ccp( player.position.x + [joystick xValue],
player.position.y + [joystick yValue]);
This is making some assumptions about how you want your joystick and player to behave, as well as some properties of the joystick class, but hopefully you get my drift. If it isn't clear, [joystick xValue] and [joystick yValue] would be some bounded value (between -1 and 1, say) representing the touch's position on the joystick. Depending on the range of values, you may want to then scale this by some constant to move the player faster or more slowly.
The cocos2d web site has a great tutorial for beginners that I'd highly recommend. You might want to read up on the CCAction class as well for more complicated maneuvers.

Related

The turret of tank can not be turn towards the player pawn? where is the problem?

I have a simple game done using unreal engine 4,
The turret of the tank should turn toward the player pawn.
I made the blueprints code to build that, but the turret rotates quickly and incorrectly.
Video about problem
I tried to solve the problem many times without any results !!
Hope to help me.
There are probably a few ways you can do this, but you can simplify this quite a bit. I also suspect you can do all of it in the animation blueprint.
Simplify the first part (XDoMa.jpg) using the Find Look At Rotation node.
Break the output of this and create another rotator with the yaw from that node and the pitch and roll from the turret's world rotation (you're currently setting pitch and roll to zero in cDJ08.jpg, which you don't want to do in case the tank is on a slope).
To rotate the turret to point at the target, use the RInterp To node and connect its output rotator to a Set World Rotation node. The nice thing about the 'RInterp To' node is that you can set the speed. For a bit more realism you could use some simple maths to accelerate and decelerate the turret's rotation.
Another thing you'll want is a bool variable in the tank actor BP. Then you can use a branch in the animation BP to trigger the stuff above when you set the bool to true.
The key parts to this are the Find Look At Rotation and RInterp To nodes, and to do all of it in the animation BP.

Best way to move a game object in Unity 3D

I'm going through a few different Unity tutorials and the way a game object is moved around in each is a little different.
What are the pros/cons to each of these methods and which is preferred for a first person RPG?
// Here I use MovePosition function on the rigid body of this component
Rigidbody.MovePosition(m_Rigidbody.position + movement);
//Here I apply force to the rigid body and am able to choose force mode
Rigidbody.AddForce(15 * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
// Here I directly change a transforms position value, in this case the cam
Transform.transform.position = playerTransform.position + cameraOffset;
Thanks!!
EDIT;
Something I have noticed is that the applied force seems to memic wheeled vehicles while the position changes memic walking/running.
RigidBodies and Velocities/Physics
The only time, I personally have used the rigidbodys system was when implementing my own boids (flocking behaviour) as you need to calculate a few separate vectors and apply them all to the unit.
Rigidbody.MovePosition(m_Rigidbody.position + movement);
This calculates a movement vector towards a target for you using the physics system, so the object's velocity and movement can still be affected by drag, angular drag and so on.
This particular function is a wrapper around Rigidbody.AddForce I believe.
Pros :
Good if realistic physical reactions is something you are going for
Cons:
A bit unwieldy to use if all you are trying to achieve is moving a object from point A to point B.
Sometimes an errant setting set too high somewhere (for example: Mass > 10000000) can cause really screwy bugs in behaviour that can be quite a pain to pin down and mitigate.
Notes: Rigidbodies when colliding with another Rigidbody would bounce from each other depending on physics settings.
They are also affected by gravity. Basically they try to mimic real life objects but it can be sometimes difficult to tame the objects and make them do exactly what you want.
And Rigidbody.AddForce is basically the same as above except you calculate the vector yourself.
So for example to get a vector towards a target you would do
Vector3 target = target.position - myPosition;
Rigidbody.AddForce(target * 15 * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
If you don't plan on having any major physics mechanics in your game, I would suggest moving by interpolating the objects position.
As it is far easier to get things to behave how you want, unless of course you are going for physical realism!
Interpolating the units position
Pros :
Perhaps a little strange to understand at first but far simpler to make objects move how you want
Cons:
If you wanted realistic reactions to objects impacting you'd have to do a lot of the work yourself. But sometimes this is preferable to using a physics system then trying, as I've said earlier to tame it.
You would use the technique in say a Pokemon game, you don't stop in Pokemon and wait for ash to stop skidding or hit a wall and bounce uncontrollably backwards.
This particular function is setting the objects position like teleporting but you can also use this to move the character smoothly to a position. I suggest looking up 'tweens' for smoothly interpolating between variables.
//change the characters x by + 1 every tick,
Transform.transform.position.x += 1f;
Rigidbody.MovePosition(m_Rigidbody.position + movement);
From the docs:
If Rigidbody interpolation is enabled on the Rigidbody, calling Rigidbody.MovePosition results in a smooth transition between the two positions in any intermediate frames rendered. This should be used if you want to continuously move a rigidbody in each FixedUpdate.
https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
Rigidbody.AddForce(15 * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
This will make the object accelerate, so it won't travel at a constant velocity (this is because of Newton's second law, Force=mass*acceleration). Also if you have another force going in the opposite direction this force could get cancelled out and the object won't move at all.
Transform.transform.position = playerTransform.position + cameraOffset;
This will teleport the object. No smooth transition, no interaction with any forces already in the game, just an instant change in position.

Unity 2D Bounce Back moving object when colliding with another object

I have an object that, after receiving its respective input, it moves this way:
mov = new Vector3((Input.GetAxis("Horizontal") * vel), 0, 0);
transform.position += mov;
But, I want it to bounce back, once it collides with an object.
I´ve made the procedures already (OnCollisionEnter2D(Collsion2D col){bla bla...}), but I need help with what happens on the collision (bouncing back the object)....
I´ve tried giving the collided object a bouncing material, but it just slows it a bit, my guess is that because of the constant force given by the acceleration.
Greetings.
If you move the object with transform.position what you are doing is basically a "teleport" so it will ignore the bouncing material. If you want it to bounce you have to write the physics code to detect a collision and change the movement or you can do addforce to move the object and it will detect collisions and react automatically.
you are teleporting the object at the current time. instead you should use the Rigidbody.addForce this will add a force in the specified direction thus if you do the opposite direction will "bounce" of the object. Another option would be to create a physics material then not bother with the code.
You are not using materials, right?
See if the content of this post may help you, the OP is using a formula using Raycast and the answer guides him to use the Raycast with Layers Maks:
2D bouncing formula doesn't work properly
There is this one also with fixed angles (like Pong), but it uses material (with values: friction: 0, bounciness: 1):
https://gamedev.stackexchange.com/questions/70294/get-gameobject-to-bounce-of-colliders
But if nothing makes sense and you are going crazy and might want to start from zero, there is this official video tutorial on bouncing and sliding in 2D:
https://unity3d.com/learn/tutorials/modules/beginner/2d/sliding-bouncing-2d

How to make a sprite have gravity?

xcode 5 iOS7 sprite kit.
My wish is to make a sprite that has its own gravity.
Like a planet. If another sprite comes within a certain range of it, it will slowly pull the other sprite closer.
I have two sprites. One moving and one stationary. When the moving sprite gets in a given distance of the stationary sprite the stationary sprite gravity should slowly pull the other sprite towards it. This way the moving sprite would change its path in a soft curve.
My idea would be to calculate the distance from the stationary object to any other object and if close enough start pulling and if the moving object gets out of range ageing, then stop pulling.
Would probably need to research some vector calculation.
Thats my immediate thoughts.
Is this possible and how? Does it already exist?
A friend of mine did this for his physics dissertation. multibody gravity simulation. So yeah you can but you need to be willing to learn some maths. Apparently there is a clever optimisation to make it run decently nlog(n) rather than n^2). you probably want to ask this on the physics version of stack overflow to get a good answer. I have the code at home ... will post it later but you will want an explanation - i used it in an xna app. Its badass once you get it working - although if you want naturally orbiting objects then you will want to code them using parametric equations for easy and cool orbits. Simply because its hard to solve and with time even using double will result in some errors (the good implementations also work out the error and adjust - again will post later). But the real problem is solving for stable orbits. You then use the algorithm for free moving bodies such and player objects / npcs. Although solving accurate movement for npc in a changing field is v hard.
you want to look at this question: Jon Purdys answer is the one you want
multi body physics - gravity
and this one (which is linked from above) ...
https://gamedev.stackexchange.com/a/19404
There is not a dead-simple way of doing that in any platform as far as I know maybe except for some game engines/platforms that export for different platforms (cocos2d, construct 2 etc).
What you need is a physics engine whether you write one (which is a complicated but fun thing to do) or use an available one.
Luckily I've found a link describing the usage of the famous 2D physics engine "Box2D" on iOS.
This one explains how you can include Box2D in an openGL application (but you can apply this to other environments (sprite kit) I think altough I'm not an iOS guy);
http://www.iforce2d.net/b2dtut/setup-ios
Anyways, you now know what to look for...
For iOS 8.0+ : you have SKFieldNode : radialGravityField()
For iOS 8.0- : one solution could be : 3 to 9
add your sprite ( planet ) with its physics
add an invisible SKNode ( the gravity zone ) with its own physics, as a child of your sprite, but with a radius much more than your sprite's one
you have a little explanation about invisible node here : https://developer.apple.com/documentation/spritekit/skphysicsworld
both, your sprite and the invisible node are centered in a zero gravity world
we look for contact and not collision ( set correctly your bit masks )
when any object get in contact with the invisible node ( gravity zone ), first you remove any moving action or impulse from it and then we add to this object an SKAction to move it toward the center of your sprite ( planet )
at second contact between this object and your sprite ( planet ), you remove all actions again from the object with a velocity = zero

iPhone OpenGL ES: Firing a bullet and detecting if it hit an object

I have worked out how to detect touching on an object using glReadPixels but how would I detect if a object hits another object (a bullet for example).
I cant do that with detecting colours.
As others have said, do this in the object model, not in the graphics.
For one simple model, give each object other than a bullet a size. Then check if a bullet's location is within that object's radius every tick. In pseudocode:
for each bullet
for each hittableObjectInWorld
if ([hittableObject isTouchedBy:bullet]) {/*handle collision*/}
endFor
endFor
hittableObject::isTouchedBy:(Sprite *)otherObject {
xDistance = [self x] - otherObject.x;
yDistance = [self y] - otherObject.y;
totalDistance = sqrt((xDistance*xDistance) + (yDistance*yDistance));
if (totalDistance <= [self size]) return YES;
else return NO;
}
Now you've got a simple collision detection system. There are some abstractions here: We treat every hittable object as if it were shaped like a sphere with its 'size' as its radius. Bullets are pinpoint small, but you can correct for that by adding a bullet's radius to the radius of each of the hittable objects and it makes the math run a wee bit faster this way.
This might be the simplest possible collision detection system. There's a lot of room for improvement here. The big thing is you're doing the number of bullets times the number of hittable objects checks each tick. If you have many bullets and many objects in the world, that can be a lot of processor time. There's all sorts of hacks to cut down on the number of checks you have to do. If you run into speed problems with this version, that's the next thing to start tuning up.
Good luck!
You do it in your object model, not in your graphics code. OpenGL is only tangentially related to collision detection.
OpenGL only deals with the graphical display of your game's objects. Any logic about how the objects in your game behave should be done in the code that manages the state of the objects not in the OpenGL graphics code.
What you are looking for is collision detection which can be a fairly deep topic. Just to be clear, once you detect a collision (e.g. a bullet hitting an object) you will more than likely run some OpenGL code to display the reaction of the collision to the user but the actual detection of the collision should not occur within the OpenGL realm.
Lastly, if you find all of this a bit overwhelming I would recommend the use of a game engine like cocos2d or Unity.