I have a scene set up where the player moves and rotates with Virtual Joystick Input. I have button which rotates the camera to the back of my player at that point I want to change the joystick input direction so it moves my player to towards its current forward direction.
The joystick Scripts:
1) script to handle events:
public class joystickEvents extends EventSystems.EventTrigger{
var position:Vector2=Vector2.zero;
public var joyStickHolder:Transform;
private var pointerUp:boolean=false;
function Update(){
if(position!=Vector3.zero && pointerUp){
position=Vector3.Lerp(position,Vector3.zero,5*Time.deltaTime);
}
}
public function OnDrag(data:EventSystems.PointerEventData){
position=data.position-joyStickHolder.position;
}
public function OnPointerUp(data:EventSystems.PointerEventData){
pointerUp=true;
}
public function OnPointerDown(data:EventSystems.PointerEventData){
pointerUp=false;
}
}
2) script for joystick movement:
public class joystick extends MonoBehaviour{
var joystickEvents:joystickEvents;
var joystickHolder:RectTransform;
var dir:Vector3;
private var maxDist:float;
private var direction:Vector3;
private var magnitude:float;
function Start(){
maxDist = joystickHolder.sizeDelta.x;
maxDist=maxDist/2.5;
}
function OnGUI () {
if(joystickEvents.position.magnitude>(maxDist))
magnitude=maxDist;
else{
magnitude=joystickEvents.position.magnitude;
}
direction=joystickEvents.position.normalized;
transform.localPosition=direction*magnitude;
dir=direction*(magnitude/maxDist);
}
}
The player controller script takes the variable dir
to move around the world. I think this value must changed somehow to so that move the player moves towards its current forward based on joystick input when camera is rotated.
Here some part of playerController responsible for player movement:
public class charcterController extends MonoBehaviour{
private var controller : CharacterController;
private var moveDirection : Vector3 = Vector3.zero;
var speed : float = 6.0;
var joystick:joystick; //reference to the joystick script
function Start(){
controller = GetComponent.<CharacterController>();
}
function Update() {
var joyInput:Vector3=joystick.dir; //the dir in joystick script
dir=Vector3(joyInput.x,0,joyInput.y);
if (controller.isGrounded) {
moveDirection = dir;
moveDirection *= speed;
controller.Move(moveDirection * Time.deltaTime);
rotate();
}
function rotate(){
if(dir!=Vector3.zero)
transform.rotation = Quaternion.LookRotation(dir);
}
}