- Home /
Question by
MilkX5 · Jan 17, 2014 at 03:36 PM ·
collision3dcharactercontrollertranslate
3D Collision with Transform.Translate
I'm using transform.Translate as well as a Character Controller for my 3D player and a rotating camera controlled by the mouse. The movement for the character works fine as long as I use transform.Translate for the movement and Character.Move for the jumping. The CharacterController doesn't work well for movement because it isn't relative to the camera. Is there anyway I can make collisions with the world while using transform.Translate or is there another solution to movement while still being relative to the camera?
Here is my code so far
//Player 1
var gravity : float = 20.0; //set gravity variab;e
var hopValue : float = 0.0;
var moveSpeed : float = 5.0; //set movement speed
var jumpSpeed : float = 10.0; //set jump height
var velocity : Vector3 = Vector3.zero; //set velocity variable for 3d movement
var FPcamera : GameObject; //define first person camera
var TPcamera : GameObject; //define third person camera
var startPos : Transform; //define start position for player
function Start(){ //starting function called when player is instantiated
FPcamera.active = true; //activate first person camera
TPcamera.active = false; //deactivate third person camera
}
function Update () { //constantly updated function called every frame
var controller : CharacterController = GetComponent(CharacterController); //define character controller from the collision body
var transLR : float = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime; //define left and right movement by the horizontal axis keys
var transFB : float = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime; //define forward and backward movement by the vertical axis keys
if(controller.isGrounded){ //if player is on the ground
if(Input.GetButton("Jump")){ //if pressing the jump button
velocity.y = jumpSpeed; //move up by jump speed
}
}
transform.Translate(transLR, 0, transFB); //move by the left, right, forward, and backward movements
velocity.y -= gravity * Time.deltaTime; //apply gravity
controller.Move(velocity * Time.deltaTime); //always move the character controller
//cameras
if(Input.GetKeyDown("q")){ //if pressing the q key
FPcamera.active = !FPcamera.active; //toggle first person camera
TPcamera.active = !TPcamera.active; //toggle third person camera
}
transform.Rotate(0,Input.GetAxis("Mouse X") * 5, 0); //rotate body based on mouse x axis
Screen.lockCursor = true; //lock the cursor on the screen
}
function OnTriggerEnter(other : Collider){ //function for entering object with a trigger
if(other.tag == "kill_Zone"){ //if the object is a kill zone
this.transform.position = startPos.transform.position; //restart position to the start position
}
}
Comment