- Home /
making a mushroom trampoline , bouncing the gameobject relative to mushroom's rotation
I am trying to make a 2D mushroom trampoline mechanism so far i have got it working only if mushroom is perpendicular to ground if the mushroom is rotated to like 60° on z Axis then the results achieved are not desirable here is an image for what i am trying to achieve
My current code is given below
public GameObject Rogue;
public float strength;
// THIS SCRIPT IS ATTACHED TO MUSHROOM GAMEOBJECT
void OnCollisionEnter2D(Collision2D other){
if (other.gameObject == Rogue){
Rogue.GetComponent<Rigidbody2D>().AddForce(transform.up * strength);
}
}
Answer by Durstie · Sep 18, 2020 at 11:01 PM
Your transform is only in the up direction. I'm assuming your current results are that it only bounces you upward. You will probably want to create a vector variable that stores the direction you want your force applied to and use that instead of tansform.up when you add the force.
As an example try this: Rogue.GetComponent().AddForce(new Vector2(1,1) * strength);
@Durstie yea i can definitely do that manually but i am looking for a way in which i can create multiple instances and don't need to change a thing and for that there needs to be a relation between rotation and force.
@JackhammerGa$$anonymous$$g How are you setting the rotation on your mushroom? Could you take the rotation of the rigidbody and convert that to a Vector2?
Something like this maybe?
private Vector2 forceVector;
void Start()
{
forceVector = DegreeToVector2(Rogue.GetComponent<Rigidbody2D>().rotation);
}
void OnCollisionEnter2D(Collision2D other){
if (other.gameObject == Rogue){
Rogue.GetComponent<Rigidbody2D>().AddForce(forceVector * strength);
}
}
public static Vector2 RadianToVector2(float radian)
{
return new Vector2($$anonymous$$athf.Cos(radian), $$anonymous$$athf.Sin(radian));
}
public static Vector2 DegreeToVector2(float degree)
{
return RadianToVector2(degree * $$anonymous$$athf.Deg2Rad);
}
I got this idea from this Answer
Your answer
Follow this Question
Related Questions
how to rotate a Rigidbody2D player on a moving platform. 0 Answers
Disable click action when collision 1 Answer
Rigidbody2D AddForce not working 0 Answers
Unity 2D Apply force in Z Direction 0 Answers