- Home /
Relative AddForce
Hello, I'm relatively new to Unity and was following this tutorial: https://www.youtube.com/watch?v=J1GgvDfmIo0, and in my game, you play as a sphere. The movement is done using rigidbody.addforce. This works well, but the only issue is that the movement is relative to the world, and not the camera rotation. I have a small solution, which is to add a camera direction, and multiply the movement by negative speed to make it go forwards and backwards. This works, but I don't know how to make it so that you can move left and right relatively.
(P.S. I have another problem that is caused by the camera direction, when the camera is colliding with an object, this makes the movement super slow. You don't have to solve this problem, but if I'm just being dumb then it would be appreciated!)
Here's my code: using UnityEngine; using System.Collections;
public class control : MonoBehaviour
{
public float speed;
public float sprintSpeed;
public float originalspeed;
Vector3 position = new Vector3(0, 1, 0);
public Transform _camera;
public bool isMoving = false;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
Vector3 cameraDirection = transform.position - _camera.position;
bool sprint = Input.GetKey("left shift");
float verticalMove = Input.GetAxisRaw("Vertical");
float horizontalMove = Input.GetAxisRaw("Horizontal");
Vector3 forceVector3 = transform.TransformDirection(cameraDirection);
if (verticalMove != 0 | horizontalMove != 0)
{
isMoving = true;
}
else
{
isMoving = false;
}
if (sprint == false)
{
speed = originalspeed;
}
if (sprint == true)
{
speed = sprintSpeed;
}
Vector3 movement = new Vector3(horizontalMove, 0.0f, verticalMove);
movement = movement + cameraDirection;
if (isMoving == true)
{
if (verticalMove > 0)
{
rb.AddForce(movement * speed);
}
if (verticalMove < 0)
{
rb.AddForce(movement * -speed);
}
}
}
}
Your answer
Follow this Question
Related Questions
How to make a ball stay in the air longer when force is added? 1 Answer
Player not Moving in Test,Debugging not Working Correctly 0 Answers
How can I make the camera to orbit also up and down ? 1 Answer
Player sometimes lags and jumps very high when instantiating prefab 1 Answer
Rotatearaound a moving object 1 Answer