- Home /
Relative AddForce With Sphere
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: 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);
}
}
}
}
Answer by Multifred · Sep 27, 2019 at 05:34 AM
So the idea is to apply a direction define in a local space into the world space! there is a method for that: https://docs.unity3d.com/ScriptReference/Transform.TransformVector.html
Vector3 movement = new Vector3(horizontalMove, 0.0f, verticalMove);
movement = camera.transform.TransformVector(movement); //we get the move in the world space
movement.y = 0; //we don't need the up component
movement.Normalize(); //we make sure the length of the vector is 1
if (isMoving == true)
{
rb.AddForce(movement * speed);
}
That should be enough to create a movement relative to the camera
Answer by kmart94 · Sep 27, 2019 at 03:06 AM
You can use transform.right to get the vector pointing directly right of the sphere relative its rotation. Here is a link to the documentation https://docs.unity3d.com/ScriptReference/Transform-right.html
You should be able to use that to get what you need. If this is helpful please upvote my most recent question at
https://answers.unity.com/questions/1667524/how-do-contact-filters-work.html