Only apply force on x and z.,How to I only add force on x and z?
So I'm going through the "Roll a Ball" tutorial and making improving it. I've made it so that the camera always looks at the ball and made it so that the ball moves relative to where the camera is looking. Only problem is that when the ball is under the camera and you move backwards, the ball levitates... How can I only apply force on the x and z?
public class CameraMovement : MonoBehaviour
{
public float speed;
public float jumpSpeed;
public GameObject player;
public Transform lookat;
public Transform direction = null;
public Rigidbody rb;
private Vector3 offset;
void FixedUpdate()
{
//Below is player movement
if (Input.GetKey("d"))
{
rb.AddForce(direction.right * speed); ;
}
if (Input.GetKey("a"))
{
rb.AddForce(direction.right * -speed);
}
if (Input.GetKey("w"))
{
rb.AddForce(direction.forward * speed);
}
if (Input.GetKey("s"))
{
rb.AddForce(direction.forward * -speed);
}
}
void LateUpdate()
{
transform.LookAt(lookat);
}
}
Answer by DarkC0der · Dec 05, 2017 at 09:53 PM
I think instead of using Input.GetKey you should use Input.GetAxis method which returns value between -1, 1. Here is the better approach.
void FixedUpdate()
{
float horizontalAxis = Input.GetAxis("Horizontal"); // Your X axis A and D keys
float verticalAxis = Input.GetAxis("Vertical"); // Your Z axis W and S keys
// Create force vector with 0 y and apply it to your rb
rb.AddForce (new Vector3 (horizontalAxis * speed, 0f, verticalAxis * speed));
}
Your answer
Follow this Question
Related Questions
The roll a ball script isn't working :(((( 2 Answers
Assigning input.acceleration to float then adding to a Vector3 to AddForce C# 1 Answer
Enemies disappear in test mode 0 Answers
How to make the ball follow the cursor? 0 Answers
How to rotate player control of ball (based on 'roll a ball' script) 0 Answers