Search Unity

Top down controller variation

Discussion in 'Scripting' started by MODEEEEE, Mar 4, 2015.

  1. MODEEEEE

    MODEEEEE

    Joined:
    Feb 15, 2014
    Posts:
    52
    Hello i have a top down controller, you can move with w,a,s,d and change rotaion of the player with the direction your mouse is point to.

    But i want to change cuz it wont gonna fit top down rpg game, i want to make that no matter what direction he is facing, when he press W he moves forward, A left , D right, based on mouse position, not just camera.

    Heres the best explanation:

    Code part:
    Code (CSharp):
    1.     void ControlMouse() {
    2.         Vector3 mousePos = Input.mousePosition;
    3.         mousePos = cam.ScreenToWorldPoint (new Vector3 (mousePos.x, mousePos.y, cam.transform.position.y - transform.position.y));
    4.         targetRotation = Quaternion.LookRotation (mousePos - new Vector3(transform.position.x, 0, transform.position.z));
    5.         transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle(transform.eulerAngles.y,targetRotation.eulerAngles.y,rotationSpeed * Time.deltaTime);
    6.  
    7.  
    8.         Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"),0,Input.GetAxisRaw("Vertical"));              
    9.         Vector3 motion = input;
    10.         motion *= (Mathf.Abs(input.x) == 1 && Mathf.Abs(input.z) == 1)?.7f:1;
    11.         motion *= (Input.GetButton("Run"))?runSpeed:walkSpeed;
    12.         motion += Vector3.up * -8;
    13.        
    14.         controller.Move(motion * Time.deltaTime);
    15.  
    16.     }
    17.  
     
  2. Timelog

    Timelog

    Joined:
    Nov 22, 2014
    Posts:
    528
    Use Transform.LookAt to make the character rotate on around his own transform by setting mousePos as the target. Then just use Input.GetAxis() to get the horizontal and vertical movement.