- Home /
Keep a rolling balls momentum
I am doing an infinite runner, the idea is to have a ball that is constantly rolling using AddRelativeTorque but I'm having a problem when it collides into the platforms. It kills the momentum and it needs to be built up again.
See the picture below, my ball has just hit the platform above it and now wont make it to the next platform, resulting in game over.
Is there a way I can hit the platform without losing the speed of the ball?
Here is my code:
using UnityEngine;
using System.Collections;
public class platform : MonoBehaviour
{
public Rigidbody target;
public float speed = 5f;
public int jumpHeight = 6;
public bool isFalling = false;
private bool isJumping = false;
// Update is called once per frame
void Update ()
{
if(Input.GetKeyDown(KeyCode.R))
{
Application.LoadLevel(0);
}
if(Input.GetButtonDown("Fire1") && isFalling == false)
isJumping = true;
}
// Update is called once per frame
void FixedUpdate ()
{
ballMovements ();
}
void ballMovements()
{
rigidbody.AddRelativeTorque(Vector3.right * -1 * speed);
//transform.Translate(1f * Time.deltaTime, 0f, 0f);
if( isJumping )
{
isJumping = false;
Debug.Log ("clicked");
Vector3 temp = rigidbody.velocity;
temp.y = jumpHeight;
rigidbody.velocity = temp;
}
isFalling = true;
}
void OnCollisionStay()
{
isFalling = false;
}
}
Answer by Owen-Reynolds · Sep 02, 2014 at 03:02 PM
You can play directly with the sideways motion, like your current code does for jumping. Suppose you want to have a minimum sideways speed of 1M/S:
Vector3 v = rigidbody.velocity;
if(v.x<1) v.x=1;
rigidbody.velocity=v;
In theory, this would be in FixedUpdate, to be sure it resets speed before each move. But in Update would probably be fine.
Of course, you can have all sorts of fancy programming in the middle. Say you want it to bounce backwards, but then always climb some more. Remember it's furthest progress, when it hits something new, set a 1-second counter; and if it's past the time and in "old" territory, force (or smooth) the speed to 1.
Thanks ill mess around with this and see what I can come up with, thanks :)
Your answer
Follow this Question
Related Questions
Velocity powered rigidbody on a moving platform without parenting. 3 Answers
Player parent to platform problem 0 Answers
Climb Down Ladder in 2D Platformer Game 1 Answer
Is it possible to increase stopping distance with forcemode.velocitychange? 0 Answers
Continuing the momentum of the rigidbody 0 Answers