TransWikia.com

Need a little more help with rotating sword around player (Unity 2D)

Game Development Asked by Gus K on December 23, 2020

this question is somewhat similar to my last question (found here). This time, I have upgraded to the new Input Manager and updated the script that uses the controller, but now I’m having trouble with having the sword rotate around the player and towards the mouse. The image below might help visualize this better.
Crudely drawn picture of a sword rotating around a player towards mouse
Here’s my current code:

public void Update()
{
    var gamepad = Gamepad.current;
    var mouse = Mouse.current;
    if (controllerControl)
    {
        x = gamepad.rightStick.ReadValue().x;
        y = gamepad.rightStick.ReadValue().y;
    }
    else
    {
        x = mouse.position.ReadValue().x; //Here's where I think the problem is
        y = mouse.position.ReadValue().y;
    }
    

    
    //convert the input into an angle in radians, and convert that into degrees
    float rads = Mathf.Atan2(y, x);
    float degrees = rads * Mathf.Rad2Deg;

    //use trig to position sword
    sword.localPosition = new Vector3(Mathf.Cos(rads) * distance, Mathf.Sin(rads) * distance, 0);
    //rotate to face away from center. note that the angle atan gives us is
    //oriented differently than unity's rotation, so we have to reverse it 
    //and add 90.
    sword.localEulerAngles = new Vector3(0, 0, degrees - 90);
}

The boolean "controllerControl" will change based on which input device the player chooses. The sword is a child of a box object. If someone could point me in the right direction, that would be much appreciated.

One Answer

I found the answer by myself, but if this is not best practice then please let me know.

var gamepad = Gamepad.current;
    var mouse = Mouse.current;
    if (controllerControl)
    {
        x = gamepad.rightStick.ReadValue().x;
        y = gamepad.rightStick.ReadValue().y;
    }
    else
    {
        Vector3 v2 = cam.ScreenToWorldPoint(new Vector3(mouse.position.ReadValue().x, mouse.position.ReadValue().y, cam.nearClipPlane));
        x = v2.x - box.transform.position.x;
        y = v2.y - box.transform.position.y;
      
    }

This solution requires a new Camera 'cam' if someone else wants to use this.

Correct answer by Gus K on December 23, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP