在Unity2d中将rigidbody.velocity设置为鼠标的方向 [英] Set rigidbody.velocity to direction of mouse in Unity2d

查看:138
本文介绍了在Unity2d中将rigidbody.velocity设置为鼠标的方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在 unity 2d 中将rigidbody.velocity 设置为鼠标指针的方向.我需要物体的初始速度在那个方向.之后,它将受到重力的影响.这是我尝试过的:

I am wondering how to set the rigidbody.velocity to the direction of the mouse pointer in unity 2d. I need the objects initial velocity to be in that direction. Afterward, it will be affected by gravity. Here is what I tried:

float maxVel = 10f
float posTotal = Input.mousePosition.x + Input.mousePosition.y
float xVel = Input.mousePosition.x / posTotal
float yVel = Input.mousePosition.y / posTotal
Vector3 velTotal = new Vector3(xVel * maxVel, yVel * maxVel, 0)

我反复尝试过,但物体似乎朝随机方向发射.

I have tried this repeatedly, but the object seems to fire in a random direction.

推荐答案

首先将两个鼠标轴相加,这不会创建 Vector2.用

First you add up your two mouse axis and that does not create a Vector2. Test it with

Debug.Log(Input.mousePostion.x);
Debug.Log(Input.mousePostion.y);
Debug.Log(posTotal);

总和没有什么意义.

改为使用 Camera.ScreenToWorldPointhttps://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html

然后像这样从那个 WorldPoint 中减去 player.positionhttps://docs.unity3d.com/Manual/DirectionDistanceFromOneObjectToAnother.html

and substract the player.position from that WorldPoint like this https://docs.unity3d.com/Manual/DirectionDistanceFromOneObjectToAnother.html

获得方向.您可以使用该操作中的 Vector3 在该方向上应用速度.

to get a direction. You can apply a velocity in that direction with the Vector3 from that operation.

祝你好运

这篇关于在Unity2d中将rigidbody.velocity设置为鼠标的方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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