如何以特定速度将精灵的速度设置为与鼠标指针相反的方向?

时间:2019-01-29 16:57:03

标签: c# unity3d

/ *我正在Unity中制作一个2D游戏,该游戏的工作原理与台球类似,但具有其他方面。当玩家按住按钮0时,一条线从球上拖开,以显示将击入球的方向和速度。我不知道如何设置该速度或如何添加这样的力。

我尝试直接设置速度,然后添加假的摩擦,但是效果不是很好。我还尝试过向球施加力,还制作了一个空的游戏对象,该对象跟随指针并带有点效应器以击退球。但是我似乎什么也无法工作。       -我也为代码混乱感到抱歉,对此我还是有点陌生 * /

using System.Collections;
 using System.Collections.Generic;
using UnityEngine;

public class LineDrawer : MonoBehaviour
{
public Transform tr; //this is the transform and rigid body 2d of the 
ball
public Rigidbody2D rb;
public LineRenderer line; // the line rendered is on the ball 
public float hitForce = 10;
// Start is called before the first frame update
void Start()
{
    line = GetComponent<LineRenderer>();
    line.SetColors(Color.black, Color.white);

}

// Update is called once per frame
void FixedUpdate()
{
    line.SetPosition(0, tr.position - new Vector3(0, 0, 0));

    if (Input.GetMouseButton(0)&&PlayerPrefs.GetInt("Moving")==0)
    {
        line.SetWidth(.25f, .25f);
        line.SetPosition(1, Camera.main.ScreenToWorldPoint(Input.mousePosition));
        float len = Vector2.Distance(line.GetPosition(0), line.GetPosition(1)); //this is for determining the power of the hit


    }
    else
    {
        line.SetWidth(0, 0); //make the line invisible
    }
    if (Input.GetMouseButtonUp(0) && (PlayerPrefs.GetInt("Moving")==0))
    {
        Vector2.Distance(Input.mousePosition, tr.position)*100;
         Debug.Log("Up");
        rb.velocity = //this is what i cant work out
         PlayerPrefs.SetInt("Moving", 1);

    }
}

}

从底部开始

// 5行是我设置速度的地方。

1 个答案:

答案 0 :(得分:0)

enter image description here

只需将脚本重写为以下内容:

using UnityEngine;

public class Ball : MonoBehaviour
{

    private LineRenderer line; 
    private Rigidbody2D rb;

    void Start()
    {
        line = GetComponent<LineRenderer>();
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        line.SetPosition(0, transform.position);

        if (Input.GetMouseButton(0))
        {
            line.startWidth = .05f;
            line.endWidth = .05f;
            line.SetPosition(1, Camera.main.ScreenToWorldPoint(Input.mousePosition));           
        }
        else
        {
            line.startWidth = 0;
            line.endWidth = 0;
        }

        if (Input.GetMouseButtonUp(0))
        {
            Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
            direction.Normalize();
            rb.AddForce(direction * 3f, ForceMode2D.Impulse);       
        }
    }
}