Home > front end >  Please help get rid of this copying
Please help get rid of this copying

Time:04-22

How can i shorten this code and avoid copying, what do you advise?

The method is used to move the camera in space using buttons

 private void HandleMovementInput() {
        
        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
        {
            new_position  = (transform.forward * movement_speed);
        }

        if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
        {
            new_position  = (transform.forward * -movement_speed);
        }

        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            new_position  = (transform.right * movement_speed);
        }

        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            new_position  = (transform.right * -movement_speed);
        }

        
        if (Input.GetKey(KeyCode.Q))
        {
            new_rotation *= Quaternion.Euler(Vector3.up * rotation_amount);
        }

        if (Input.GetKey(KeyCode.E))
        {
            new_rotation *= Quaternion.Euler(Vector3.up * -rotation_amount);
        }
        //Shit code for zoom

        if (Input.GetKey(KeyCode.R))
        {
            new_zoom  = zoom_amount;
        }

        if (Input.GetKey(KeyCode.F))
        {
            new_zoom -= zoom_amount;
        }

        transform.position = Vector3.Lerp(transform.position, new_position, Time.deltaTime * movement_time);
        transform.rotation = Quaternion.Lerp(transform.rotation, new_rotation, Time.deltaTime * movement_time);
        camera_transform.localPosition = Vector3.Lerp(camera_transform.localPosition,new_zoom, Time.deltaTime * movement_time); 
}

Unfortunately, I'm not so strong in Unity to solve this architectural case)

CodePudding user response:

Try using Input.Getaxis.

https://docs.unity3d.com/ScriptReference/Input.GetAxis.html

I used this code for my player movement script

//playerinput is a Vector3 variable
playerinput = new Vector3(Input.GetAxis("Horizontal"), 0f, 
Input.GetAxis("Vertical"));
//transform.TransformDirection is here to move the player depending in their rotation
//playerinput.normalized is there for stopping strafing(for example, holding w and s together makes the player faster)
//I don't think you should change Mathf.Clamp01(playerinput.magnitude). This is very important for the movement to look good.
  Vector3 movevector = transform.TransformDirection(playerinput.normalized * Mathf.Clamp01(playerinput.magnitude)) * speed;
    
    //rb is the rigidbody by the way. Add rigidbody component to your camera
    rb.velocity = new Vector3(movevector.x, rb.velocity.y, movevector.z);

This will do the trick, you can remove some lines of code to fit your game. Hope this helped!

  • Related