- Home /
Problem with free 3D - movement script
Hi. This is kinda hard to explain but I´ll try.
I´m creating a sort-of space shooter which requires free movement in all 3 dimensions. I want the movement to be like in Dark Souls, but in 3D space.
I got everything running for moving in the XZ-Plane but I can´t figure out how to do it correctly for 3 dimensions.
As soon as the camera looks up or down and I move forwards or backwards, everything seems alright but as soon as I try to move left or right, everything becomes a mess.
Here´s my controls script:
class Controls extends MonoBehaviour{
public var moveDirection:Vector3;
public var moveSpeed:int = 10;
public var cameraTransform:Transform;
public var inputParser:InputParser;
public function Update():void{
this.freeMove();
this.genericMove();
this.cameraTransform.position = this.transform.position;
}
public function freeMove():void{
var right = this.cameraTransform.right;
var forward = this.cameraTransform.forward;
var v = this.inputParser.verticalLeftStick;
var h = this.inputParser.horizontalLeftStick;
moveDirection = v * forward + h * right;
moveDirection = moveDirection.normalized;
if(moveDirection != Vector3.zero){
transform.rotation = Quaternion.LookRotation(moveDirection);
transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed);
}
}
public function genericMove(){
this.GetComponent.<Rigidbody>().velocity = Vector3.zero;
if(this.inputParser.yHold){
this.transform.localPosition.y += this.moveSpeed * Time.deltaTime;
}
if(this.inputParser.aHold){
this.transform.localPosition.y -= this.moveSpeed * Time.deltaTime;
}
}
}
And here´s the Camera controls script:
class CameraControls extends MonoBehaviour {
public var rotationSpeed:int = 10;
public var target:Transform;
public var normalAnchor:Transform;
public var leftAnchor:Transform;
public var rightAnchor:Transform;
public var cameraAnchor:Transform;
public var inputParser:InputParser;
public function LateUpdate(){
this.parseInput();
}
private function parseInput(){
var rotationY = this.inputParser.horizontalRightStick * this.rotationSpeed * Time.deltaTime;
var rotationX = this.inputParser.verticalRightStick * this.rotationSpeed * Time.deltaTime;
this.cameraAnchor.transform.Rotate(rotationX, rotationY, 0);
Camera.main.transform.position = this.normalAnchor.position;
Camera.main.transform.rotation = this.normalAnchor.rotation;
}
}
What is the trick to make it work right? I can provide an example project with this if needed.
EDIT #1: I also noticed that the camera rotation isn´t working correctly either.
Your answer
Follow this Question
Related Questions
Limit object position which is moved by accelerometer 0 Answers
MoveTowards inside Coroutine 2 Answers
Smooth motion physics Playmaker 0 Answers
Character drifts, moves the wrong way 1 Answer
Convert WASD to local rotation 1 Answer