用鼠标拖动左右移动球Unity 3D

时间:2018-12-23 18:48:32

标签: c# unity3d

我有一个连续跳动的球,我想用鼠标在x轴上左右移动它,以便它跟随鼠标的X移动。

我把脚本放到了下面,但是用鼠标却没有动球!

球形脚本:

private Vector3 pos;
public Camera cam;

public Rigidbody Ball;
public float Speed;
public static float GlobalGravity = -9.8f;
public float GravityScale = 1.0f;
bool isforce = false;

private void Start(){

    Ball = GetComponent<Rigidbody>();
    Ball.useGravity = false;

}


private void FixedUpdate(){

    Vector3 gravity = GlobalGravity * GravityScale * Vector3.up;
    Ball.AddForce(gravity, ForceMode.Acceleration);

}

void force (){

    isforce = false;
    Ball.AddForce(Vector3.up * Speed, ForceMode.Impulse);
}

private void Update(){

    if (isforce == true){

        force();
    }

    if (Input.GetMouseButton(1)){

        Vector3 mousePos = Input.mousePosition;
        Vector3 wantedPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, transform.position.y, 10));
        transform.position = wantedPos;
    }
}

private void OnCollisionEnter(Collision collision){

    isforce = true;
}

1 个答案:

答案 0 :(得分:0)

尝试一下,让我知道会发生什么。您的按钮设置为右键单击,但是我将其改为左键单击,除了我只是将球x放置在鼠标输入的原始x上。

private void Update(){

    if (isforce == true){

        force();
    }

    if (Input.GetMouseButton(0)){

        Vector3 mousePos = Input.mousePosition;
        Vector3 wantedPos = transform.position;
wantedPos.x=Input.mousePosition.x;
        transform.position = wantedPos;
    }
}