How to make my sprite Jump? (XNA, C#) - c#

I've been working on a simple platformer game using XNA. I have been having some trouble working out a good jumping algorithm. After getting rid of the messy half done versions of the jumping algorithm all I have left is.
if (keystate.IsKeyDown(Keys.W))
{
spritePosition.Y = spritePosition.Y - 10;
}
I realise this is a very unsophisticated start but any tips would be great. I'm a self taught programmer so some terminology might be lost on me, I tend to find looking at actual code the best way to learn. Thanks.

When you jump (physically) you are adding an amount to your Y velocity vector, not to your position vector. Moving your position by 10 means you're just teleporting upward 10 ticks.
Try adjusting velocity, then letting your main loop change the position. And remember acceleration downward from gravity!
Edit: Added link from comment below to physics tutorial. rodedev.com/tutorials/gamephysics

Try following:
if(Input.GetKeyDown(KeyCode.W))
{
// your code here
}
It will make it so that every time the player presses W, they will only go until they can press W again. You can always set Rate of Jump and make it so that they can only jump once every so and so seconds.

Related

How can i make a rigidbody speed up everytime it collides with a wall at an angle?

I am trying to make a game where i got a ball with an arrow rotating around it. The ball starts as immovable, but when i hit a button i launch it to the direction the arrow is pointing at. Player will have the option mid air to press another button to make the ball "sticky" so when it hits a wall it will stick to the surface and repeat the process till he gets to the top of the level.
Aside from that, i want to give the option to the player to not stick to the wall if he doesn't press that button and instead bounce off the wall but when he does that, the player should speed up with every bounce, giving the option to either play it safe and slow or try to go fast getting more points as he does.
For the early prototyping i used force to move the player up every time he launches but i am not sure how i can make him speed up every time he bounces off the wall. It feels to me like a math problem more than it is a coding challenge. What i am thinking is that i have to find the angle on which player hits the wall, and add force according to that towards the direction he is supposed to follow after the collision.
Sadly i am not that good with trigonometry (working on it though). I am thinking that i might need to use a formula containing sin, cos, tan formulas but i m not sure how to do it. Any help is much appriciated! If you need more information on it please tell me and i ll be happy to provide.
Edit: After the first reply to this question i also found out those links that dive deeper into the subject. I m gona link them here for people that have the same issue.
Bouncing a ball off a wall with arbitrary angle?
http://www.3dkingdoms.com/weekly/weekly.php?a=2
If your ball has velocity vector V=(vx,vy), then after bouncing from standing surface with normal N, ball's new velocity is
V' = V - 2 * N * (V.dot.N)
where dot is scalar product of vectors (vx*nx+vy*ny)
Particular cases:
bouncing from vertical wall (N=(+-1, 0)) causes reversing of vx-component, vy component remains the same. V' = (-vx, vy)
bouncing from horizontal wall (N=(0, +-1)) causes reversing of vy-component, vx component remains the same. V' = (vx, -vy)
Note I recommend to work in velocity vector components, and use angles only when they are really needed.
If you need to calculate bouncing from moving bat, it is worth to change stationary coordinate system to moving one, connected with the bat, find reflection in that system, and revert to stationary system.
Ok so problem was solved!
I want to thank both #MBo and #shingo for their contribution to the solution. While the answer of Mbo solved the problem via trigonometry and gave me nice material to study and figure out how things work, i followed shingo's advice in the comments of my question and managed to do it without diving deep into math.
So basically what he said, and what i did, was to use Unity's physics engine and let the ball hit the wall. After the ball bounces off the wall, it gets a new Velocity vector towards the direction it would go based on physics. I then created an OnColllisionExit check, and when the ball stops colliding with the wall, i AddForce to it to the direction of its new Velocity Vector3.
Works like a charm!
Thank you all for your contributions!

How to handle multiple rocket thrusters?

I'm fairly new to game development and I'm trying to develop a 2D game in unity where the main character has a jetpack with two thrusters and I want him to control each one individually. So if he only turns on one thruster he goes 5 meters above ground and hovers there while using both would make him hover at a height of 10 meters. How would i go about doing this?
I tried just simply adding forces as if the character was jumping and freezing the y-axis to 0 until he let go of the jetpack button but that did not give me the feel i was looking for. I also tried raycasting a line out of the jetpacks to the closest surface and adding a force to the jetpack to allow the player to float at that height but that I couldn't figure out a proper way to implement it.
The Raycast sounds like a great idea. Do the raycast to the next available platform and do as #Ahndwoo said in a comment, `
What you would need to do is divide the force of your thrusters by the
magnitude of the Ray. Thus, as the Ray gets longer, the force
decreases.
By doing this you'll get the natural movement from a force and you'll control how high can you get.
I would Make your thrusters holder as an object and as more turbines it has, the more powerful i'll get.

How do I fix the floating glitch that is happening to my Player Ball?

I am using Unity3D to make a replica of the game "Rolling Sky" which you can find on the Google/Apple app store. I was able to make a simple floor which the ball will move on and I was also able to make the ball (Player) move left and right. After moving the ball a couple of times back and fourth, it starts float in the air and eventually what it seems like is change it's axis.
I came up with a couple of alternatives that I think would work, but I had trouble coming up with the code to make it function properly.
1) Do not rotate the ball at all. Just have it smoothly move back and forth.
^^ Probably the best solution I could come up with.
or
2) Use CharacterController to have complete control of how the ball reacts to different events, scenarios, etc.
^^ This would probably be the most necessary and hardest of I had to guess.
or
3) Move the ball an x amount of pixels everytime I move left or right.
^^ I would assume this would create a lot more glitches than what I have right now.
public class PlayerController : MonoBehaviour
{
public float speed;
void Update()
{
transform.Translate(Vector3.right * speed * Input.GetAxis("Horizontal") * Time.deltaTime);
}
}
EDIT:
I was able to provide my own answer, but if anyone has any alternatives, feel free to post your solution!
To prevent the player ball from floating into the sky, no other code was needed. Simply go to the Rigidbody component on the Player and expand the "Constraints" menu. Next, check the axis boxes that you would like to freeze the rotation on to prevent the ball from spinning like so in the picture.
Click the link to see the picture
here.
In this case, I did not freeze the ball on the x axis because I eventually want to animate it to spin as if it is rolling forward.
You're using transform.Translate
and
You're using Vector3.right
transform.Translate will directly move the ball without thought of rotation. You will need to take the object's rotation into consideration when translating. You can also use the physics engine and use Rigidbody.MovePosition to force position or Rigidbody.AddForce to utilize physics interactions.
Vector3.right will use the constant value equivalent to Vector3(1, 0, 0). This will not be in regard to the object's rotation or facing.
I suggest looking through Unity's tutorial for a ball-roller and see how they complete the task of user input with a user controlled ball.

Adding Torque To Character With FixedAngle 2D

I've been stuck on this the last few days so I'm hoping you guys can help.
I'm making a 2D game and I want my character to slip, fall backwards, and hit his head when he tries to run on ice for too long.
My goal is to have it where if you keep holding the run button long enough on ice, he will slip backwards and damage himself.
I'm using playmaker but I do know a little c# programming.
The first thing I tried was making an animated float that adds the rotation to the Z axis over time, but that went horribly wrong and makes the character jump/skip/glitch all over the place.
The second thing I thought of was to add 2D torque to make him start slipping backwards, but he stays in the same rotation with fixedAngle true.
So then I made it where fixedAngle is false when he is on ice, but he immediately falls forward or backwards as soon as I start running. I made the center of mass right in the middle so he stands fine as long as he is not moving.
Does anybody know a way of achieving the effect I want?
This is my first game and I am a noob, so hopefully there is an easier/correct way of going about this. I could be doing this all wrong, so any guide in the right direction would be greatly appreciated.
It seems like from your verbage, you want to be tracking the amount of time the player has been running on ice.
If you want to tie this to the run key being down, start the timer if the button is down and trigger the "slip-and-fall" event to occur after a certain amount of time.
If you want to tie this to the amount of time the player has been on the ice, start the timer when the player reaches the ice and trigger the "slip-and-fall" event to occur after a certain amount of time.
If you want there to be a visual tilting, tie the time delta to the angle of the object. Set a certain angle to trigger the "slip-and-fall" event.
Update(){
if(this.running && _terrainAtPos == <Ice> && isGrounded){
transform.Rotate(0,0,3*Time.deltaTime);
if(tranform.rotation.z > 180){
//do falling event
}
}
}
EDIT: The above is not a working sample. Just something I whipped up to illustrate.

C#: How can I tell which side a collision has occured on?

I think the title is rather self explanatory but just to clarify I am trying to figure out how to tell which side the collision has occured on.
For a bit more detail, I'm trying to make a maze-like game so I can't simply stop all movement upon a collision. Instead I need to be able to tell which side the collision has happened on so I can block that direction.
Any help is appreciated and if there is a better approach to this issue, I'm all for trying it out.
I hope this is enough details but if you need anymore, ask and I'll edit. Thanks in advance.
[edit]
#viggity - No, I'm not using any specific game engine and I would post the current "detection" code but it's a little, absurdly, robust.
#Streklin - I'm using the this.Paint event to draw onto the form itself as it was recommended I start by doing that to get better at drawing real time. I'm also using a location that's updated each time the timer ticks based on what I press (left, right, up, down). Yes the maze is tile based. Currently it only consists of 3 colors even. I'm not a very advanced programmer.
#Eric - Definately a one-d game. Again, I only have 3 colors, the lines are black, the background is white and the square (the user) is green. I'm using the DrawImage() with Bitmaps to draw onto the screen.
[edit psuedo-code summary]
foreach(Wall _wall in walls)
if(player.intersectsWith(_wall))
stop movement;
#JeffH - I'm not really sure what you're asking as that's pretty much all there is besides testing code that I was using to try and get it working. The only thing I left out was the if statement to check if it was the x axis or not so that x and y could move indepedently from each other. So instead of getting "stuck" because you touched the wall, you could slide against it. I didn't see the point in including that though since the problem occurs before that.
Assuming you're talking about a 3D game here.
The normal of the face you can see points towards you, so the dot product of your direction vector with the face normal will be negative. If it's positive then you are coming at the face from the back.
If it's zero you're travelling at right angles to the face.
| <---------- your direction of travel
|
|----------> <- face normal
|
| <- face
If you're not in 3D then you could store the direction the wall is facing (as a 2D vector) and do the same dot product with your 2D direction of movement.
Based on your edit you can only go one direction at a time? Or can you go in diagonal directions? If it's the later, ChrisF has provided you the answer in 3D and the corresponding information for 2D. If not, you should just have to stop travel in the direction of travel - since there are only four possibilities it should be easy enough to check them all for simple starter game.

Categories

Resources