- Home /
Trouble rotating a character to correctly match new gravity direction
Hey, I am making a game where the player changes the direction of gravity to jump across gaps and solve puzzles. Right now I'm making it so that the player looks in the given direction they want to switch gravity to, they hit space and they tilt 90 degrees, falling to where they want to go to until they hit a wall. The issue is that they aren't falling in the correct direction every time. Sometimes they'll fall right, left, or they won't fall at all. It's very unpredictable.
Here's my script. If anyone knows how to get the player to consistently fall in the direction they are facing that would be a great help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class GravityPlayer : MonoBehaviour
{
float Grav;
float JumpForce;
float JumpTime;
public Rigidbody rb;
public float smooth = 1f;
private Quaternion targetRotation;
int Jumpmanager;
void Start()
{
Jumpmanager = 0;
targetRotation = transform.rotation;
JumpTime = 1f;
Grav = -9.8f;
JumpForce = 1f;
rb = GetComponent<Rigidbody>();
this.GetComponent<Rigidbody>().useGravity = false;
}
void FixedUpdate()
{
bool down = Input.GetKeyDown(KeyCode.Space);
if (down)
{
if (Jumpmanager < 1)
{
Jumpmanager = Jumpmanager + 1;
StartCoroutine(HandleIt());
}
}
}
private IEnumerator HandleIt()
{
Vector3 myForward = transform.TransformDirection(Vector3.forward);
rb.velocity = new Vector3(0, 0, 0);
gameObject.GetComponent<NavMeshAgent>().enabled = false;
rb.isKinematic = false;
rb.AddForce(transform.up * (JumpForce/2), ForceMode.Impulse);
targetRotation *= Quaternion.AngleAxis(90, myForward);
transform.rotation= Quaternion.Lerp(transform.rotation, targetRotation, 90 * smooth* Time.deltaTime);
yield return new WaitForSeconds(1);
rb.AddForce(transform.up * Grav, ForceMode.Impulse);
}
void OnCollisionEnter(Collision coll)
{
rb.isKinematic = true;
gameObject.GetComponent<NavMeshAgent>().enabled = true;
transform.rotation = Quaternion.identity;
Jumpmanager = 0;
}
// use the syntax if(agent.isOnOffMeshLink){ } to trigger animations and other surface switching methods
}
Your answer
Follow this Question
Related Questions
Issues with copying Y axisrotation of another object 2 Answers
Transform.eulerAngles only x and z 2 Answers
transform.Rotate vs. transform.rotation = when use which? 4 Answers
How to add limit to object rotation? 1 Answer
Transforming a single axis. 1 Answer