使用角色控制器使角色跟随鼠标

时间:2017-08-21 12:22:49

标签: c# unity3d input mouse

我有一个2D空间射击游戏(想象一下像鸡入侵者一样)已经在iOS和Android上发布。我现在正尝试将其移植到WebGL,为此,我尝试使用鼠标实现移动。以前在移动平台上使用Unity的内置字符控制器成功实现了移动,我希望继续在WebGL构建中使用它,以保持代码库小而且平台很少 - 尽可能具体实施。

因此,我应该采用什么方法让船只跟随鼠标光标?

PS: 在移动设备上,我使用了带有characterController.Move()的touch.deltaPosition让船跟随手指的移动。

编辑:当前方法

输入管理器

public Vector2 GetInput () {
        switch(type) {
            case PlatformType.Computer:
                if (Input.GetButtonDown("Jump") || Input.GetAxis("Fire") != 0f) {
                    thisDelegate.InputDidReceiveFireCommand();
                }
                if (!Input.mousePresent) {
                    temp.x = Input.GetAxis("Horizontal");
                    temp.y = Input.GetAxis("Vertical");    
                } else {
                    if (Input.GetAxis("Mouse X") != 0f || Input.GetAxis("Mouse Y") != 0f) {
                        temp.x = Input.GetAxis("Mouse X");
                        temp.y = Input.GetAxis("Mouse Y");
                    } else {
                        temp.x = Input.GetAxis("Horizontal");
                        temp.y = Input.GetAxis("Vertical");        
                    }
                }
}

的PlayerController

void HandleInput()
    {
        mvm = InputController.GetInput();
        if (GetComponent<InputManager>().type == InputManager.PlatformType.Mobile) {
            mvm *= Time.deltaTime * initialVeloc / 10;
        } else {
            if (mvm != Vector3.zero) {
                mvm -= transform.position;
            }
        }
    }

void Update () {
    characterController.Move((Vector2)mvm);
}

当前方法使字符抖动位于屏幕中心旁边。

1 个答案:

答案 0 :(得分:0)

我修改了我的脚本,现在我取的是绝对鼠标位置而不是delta。以下是它现在的样子:

输入管理器:

            if (Input.GetAxis("Mouse X") != 0f || Input.GetAxis("Mouse Y") != 0f) {
                temp = Input.mousePosition;
                temp.z = 12.5f;
                //                Vector3 initialMov = mvm;
                temp = Camera.main.ScreenToWorldPoint(temp);
                temp -= transform.position;
            }

控制器

mvm = InputController.GetInput();
mvm *= Time.deltaTime * initialVeloc;
characterController.Move((Vector2)mvm);

就CPU使用率而言,此方法与预期相同,并且似乎比RayCasting方法更有效。

相关问题