Question by
unity_x8RuehVqhSrbyw · May 23, 2020 at 11:41 AM ·
rotationvector3rigidbody2dfloatcheck
Check rotation for a Rigidbody2D
Hello, i am making a 2D game where im trying to make swimming mechanics, think DK tropical freeze.
I have rotation for the character as a vector, and when the player object reaches the desired rotation, i want to add force.
However rigidbody2D stores its rotation as a single float value that dosent wrap around. How would i go about making something that can check if the rotation of the rigidbody2D has reached its desired rotation?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Swimmer : MonoBehaviour
{
public float maxSpeed = 5;
public float rotationSpeed = 5f;
public Player player;
public Transform orientationTarget;
private Vector3 dinput;
Vector3 velocity;
Rigidbody2D rigidbody;
// Start is called before the first frame update
void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
}
}
private void FixedUpdate() {
Move();
}
public void Move() {
// if there is input
if (Input.GetAxis("Vertical") != 0 || Input.GetAxis("Horizontal") != 0) {
// get input as a vector 3
dinput = new Vector3(0, 0, Mathf.Atan2(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal")) * 180 / Mathf.PI - 90);
//rotate the rigidbody over time
rigidbody.MoveRotation(Mathf.LerpAngle(rigidbody.rotation, dinput.z, Time.deltaTime * rotationSpeed));
orientationTarget.eulerAngles = dinput;
//on the output is out problem, the rigidbodies rotation "wraps around".
//how do we make something that allows us to check if we have reached
//our desired rotation?
Debug.Log(rigidbody.rotation +" "+ orientationTarget.rotation + " "+ dinput.z);
//the problem occurs before this. But the intention of this code is to
//compare if the rigidbodies rotation is in the ballpark (-+10 degrees)
//of the target rotation.
if (rigidbody.rotation <= dinput.z -10f || rigidbody.rotation <= dinput.z +10f) {
rigidbody.AddForce(dinput*10f);
}
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612235039im_/https://answers.unity.com/themes/thub/images/avi.jpg)