Как установить скорость спрайта в противоположном направлении указателя мыши с определенной скоростью? - PullRequest
0 голосов
/ 29 января 2019

/ * Я делаю 2D игру в Unity, которая работает аналогично бильярду, но с другими аспектами.Когда игрок удерживает нажатой кнопку 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 голосов
/ 30 января 2019

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);       
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...