用鼠标拖动左右移动球Unity 3D [英] Move Ball left and right with mouse drag Unity 3D

查看:113
本文介绍了用鼠标拖动左右移动球Unity 3D的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a ball that have a continuous bouncing, and I want to move it left and right in the x Axis with the mouse, so it follow the mouse's X movement.

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

I made the script bellow, but the ball didn't move with mouse!

球形脚本:

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;
}

推荐答案

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

try this and let me know what happens. yours was set to right click, but i changed this one to left click, other than that i just sat the balls x to the raw x of the mouse input.

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;
    }
}

这篇关于用鼠标拖动左右移动球Unity 3D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆