- Home /
Accelerating speed
HI guys. I am creating a 2d game with a spaceship going up. The problem I am having is that in stead of keeping flying up while I press up, if gravity is enabled on rigidbody (which I want to be that way) The ship "jumps" instead of flying for a couple of meters and then falls down. I guess I need to code a speed acceleration, but going through different examples I can`t manage to grasp how to do it. I know it is unpolite to ask for someone to code for me, but if you could help with some advice for such a supernoob as me, I would really apprciate it.
What I have so far:`
{ public float PlayerSpeed;
// Update is called once per frame
void Update ()
{
//amount to move
float amtToMove = Input.GetAxisRaw("Horizontal") * PlayerSpeed * Time.deltaTime;
float amtToJump = Input.GetAxisRaw("Vertical") * PlayerSpeed * Time.deltaTime;
//move the player
transform.Translate(Vector3.right * amtToMove);
transform.Translate(Vector3.up * amtToJump);
//accelerate
}
}`
Just use rigidbodies for this, it's way easier. Then, just make sure that you're using enough power in AddForce to overcome gravity, and you're all good!
Answer by DavidDebnar · Oct 21, 2011 at 02:22 PM
Use rigidbody.AddForce(); function instead.
{
public float PlayerSpeed;
void Update ()
{
float amtToMove = Input.GetAxisRaw("Horizontal") * PlayerSpeed * Time.deltaTime;
transform.Translate(Vector3.right * amtToMove);
transform.Translate(Vector3.up * amtToJump);
if(Input.GetAxisRaw("Vertical") == 1)
{
rigidbody.AddForce(transform.up * PlayerSpeed);
}
}
}
David
This works exactly how I wanted it to be! Thanksm, $$anonymous$$! ^__^
This... isn't a very good solution. $$anonymous$$ixing transform.Translate with rigidbody movement is pretty dangerous.
Answer by syclamoth · Oct 21, 2011 at 11:07 AM
Do you have a rigidbody on your object? If so, you should never really use transform.Translate for anything- instead, use Rigidbody.AddForce. In your case, that would look more like-
float thrust = Input.GetAxisRaw("Vertical") * accelerationPower * Time.deltaTime;
// Spaceships only fire their rockets one way-
thrust = Mathf.Abs(thrust);
rigidbody.AddForce(transform.up * thrust);
Then just tweak accelerationPower until it feels right! For the other axis, depending on what you want to do, you would either use rigidbody.AddForce as here, or in fact rigidbody.AddTorque if you want to change your rocket's rotation.
In a pinch, rigidbody.$$anonymous$$ovePosition will work, but it's not fantastic, and physics doesn't like you very much when you do that.
Hi! Thanks for your answer! I tried it, the console shows no errors, but the object is now not moving at all and I have no idea why. Is there something else that has to be switched on? So far i have done everything with transform.translate, so I am new this (sorry :) )
You need to increase the force until it makes a difference! Presumably, your accelerationPower isn't high enough to overcome gravity.