- Home /
The question is answered, right answer was accepted
Adding speed relative to move vector (Rigidbody2D)
Hi, i'm currently working on a arcanoid clone and have a problem:
What i want: To increase the speed of my ball relative to it's movement-vector.
What i tried: A LOT. I crawled through so many answers here but got nothing to work.
Here is what i have:
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour
{
public bool hasStarted = false;
public bool tweaked;
public bool speedTweaked;
public float speed;
public Vector2 thrust = new Vector2 (0.5f, 0f);
void Update ()
{
if (!hasStarted) {
if (Input.GetMouseButtonDown (0)) {
hasStarted = true;
rigidbody2D.velocity = new Vector2 (3f, 10f);
}
if (!speedTweaked){
rigidbody2D.AddRelativeForce(thrust); // Does nothing lol
Debug.LogError("uhm..");
} else if (speedTweaked) {
rigidbody2D.AddRelativeForce(thrust); // Does also nothing omg
Debug.LogError("ok...");
}
}
}
void OnCollisionEnter2D (Collision2D col)
{
//add some randomness - this is also the cause of speed loss/ gain
Vector2 tweak = new Vector2 (Random.Range (-0.2f, 0.2f), Random.Range (-0.2f, 0.2f));
if (hasStarted) {
speed = rigidbody2D.velocity.magnitude;
Debug.Log (speed);
if (!tweaked) {
rigidbody2D.velocity += tweak;
Debug.Log ("Tweaked");
tweaked = true;
} else {
rigidbody2D.velocity -= tweak;
Debug.Log ("Tweaked");
tweaked = false;
}
if (speed <= 11) {
Debug.LogError ("Speed is under 10");
speedTweaked = false;
} else if (speed >= 12) {
Debug.LogError ("Speed is over 12");
speedTweaked = true;
}
}
}
}
I would appreciate some ideas.
Greetings
Answer by Elunius · Sep 16, 2016 at 12:41 PM
i figured out myself:
void AdjustSpeed ()
{
speed = rigidbody2D.velocity.magnitude;
if (speed < 11) {
rigidbody2D.AddRelativeForce (rigidbody2D.velocity.normalized * 10);
} else if (speed > 11) {
rigidbody2D.AddRelativeForce (rigidbody2D.velocity.normalized * -10);
}
}
Don't you want AddForce ins$$anonymous$$d of AddRelativeForce? $$anonymous$$eep in $$anonymous$$d the velocity vector is in global space, but AddRelativeForce uses local space.
Let's say your input vector(rigidbody2D.velocity.normalized * 10) equals (10f, 0f). Let's also say your object's rotation around the Z axis is 180 degrees. If you use AddRelativeForce with that input vector, you'll be making the object go left. If you use AddForce, you'll be making the object go right.
With 0 rotation on the object, they are equal. With 90 or 270 degrees rotation, it'll be going up or down respectively, with that specific input vector.
As a side note, it would be wise to use rigidbody2D.velocity.sqr$$anonymous$$agnitude ins$$anonymous$$d, since it's much cheaper to calculate due to not needing a squareroot calculation internally. If you do so, you'll have to replace "11" with "11 * 11" ins$$anonymous$$d, to get the square. The result of any greaterthan/lessthan comparisons will be the same.