- Home /
special move with a cube.
I wona to move a cube with rotate,So that the move is due to the rotation. like this image:
my code is :
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
// Use this for initialization
void Start () {
}
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
float mv = Input.GetAxis("Horizontal");
transform.Rotate(Vector3.forward,-mv);
moveDirection = new Vector3(mv* Time.deltaTime, mv* Time.deltaTime, 0);
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
how I can do it? when when player has been rotate the Axis is not work move to forward.
Using a character controller I cannot see any way to do what you want without faking it. That is, you could rotate the cube and move it up and down either using a formula or using raycasting so that it appeared to roll forward, but there would be no real physics involved.
Or you could make the cube into a Rigidbody and use AddRelativeTorque() to rotate the cube. A Rigidbody solution would have its own challenges...especially in that you would have to keep the local 'x' axis of the cube relatively parallel to the ground in order for the object to not to tip over and get stuck.
Answer by robertbu · Oct 10, 2013 at 10:29 PM
Here is a bit of source that, using a Rigidbody, will roll a cube across a plane using the arrow keys. To Use:
Create a plane
Put a cube on top of the plane
Add a Rigidbody to the plane
Add the script
#pragma strict
private var forceAmount = 40.0;
private var rotationSpeed = 45.0;
function FixedUpdate() {
transform.Rotate(0.0, rotationSpeed * Time.fixedDeltaTime * Input.GetAxis("Horizontal"), 0.0, Space.World);
rigidbody.AddRelativeTorque(Vector3(forceAmount * Input.GetAxis("Vertical"), 0.0, 0.0));
}
Note I had "Horizontal" and "Vertical" setup to use keys, not a joystick or mouse movement when I ran a brief test of this code. For general use, more code would be needed to address specific issues with the interaction of the cube and the physical environment.
Your answer
Follow this Question
Related Questions
Moving and rolling a cube 1 Answer
collider then change rotation converse? 0 Answers
orienting player in one direction 1 Answer
Directional Movement - Input position calculation? 2 Answers