Question by
akiims · Oct 19, 2015 at 12:46 PM ·
rigidbodyrigidbody.addforce
How to change rigidbody force direction?
I'm playing with Roll-a-ball tutorial. How can i modify sample code to rotate ball by y axis? I want to rotate ball forwards and change the direction using 'a' and 'd'.
Sample:
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
I tried MoveRotation, transform.Rotate, but cant get it right. I guess y axis are rotated by forward movement and y rotation are made to local y axis witch is different from world y axis?!
Comment
Answer by Nitoken · Oct 24, 2015 at 05:00 PM
I am not sure. U want move Forward/Backward by W/S and turn left/right by A/D ? I found solution (I think) in Tank unity tutorial:
using UnityEngine;
using System.Collections;
public class Mover : MonoBehaviour {
public int speed;
public int turnSpeed;
private Rigidbody rb;
void Start ()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
//For move Forward/Backward:
//moveVertical change from -1 value when pressed S and 1 when pressed W
//speed is variable
Vector3 movement = transform.forward * moveVertical * speed * Time.deltaTime;
rb.MovePosition(rb.position + movement);
//For turning left and right:
//MoveHorizontal almost same, but u use A and D key (-1 and 1 value).
//turnSpeed is variable
float turn = moveHorizontal * turnSpeed * Time.deltaTime;
Quaternion turnRotation = Quaternion.Euler(0f, turn, 0f);
rb.MoveRotation(rb.rotation * turnRotation);
}
}
Is it working?
It works if i don't use gravity. But i want to roll on to things and if the surface is steep it would be hard to get there and so on..
Your answer