Y
Y
Yura Mailler2021-07-02 19:55:33
Unity
Yura Mailler, 2021-07-02 19:55:33

How to make an object move diagonally indefinitely?

Hello! I need that when the button is pressed, the object flies diagonally until it hits the enemy (well, that is, infinitely) or rests on the platform. Show how to do this in code

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
Hixac, 2021-07-02
@Hixac

I did it more for myself, because on Habré it’s unlikely that someone will write code for someone else.
You did not mention in which dimension to write it, incl. drank for 2d. The code is working, I checked. Spherecast (This is for 3d), CircleCast (For 2d) is suitable for both cases.

public class Logic : MonoBehaviour
{
    public float Speed;
    [Header("SphereCast options")]
    public float Radius;
    private void Start()
    {
        _originalSpeed = Speed;
    }
    private void OnMouseDown()
    {
        Detector();
        Movement();
    }
    private void OnMouseUp()
    {
        Speed = 0;
    }
    private void Movement()
    {
        transform.Translate(Speed * Time.deltaTime, Speed * Time.deltaTime, 0);
    }
    float _originalSpeed;
    private void Detector()
    {
        if (Physics2D.CircleCast(transform.position, Radius, transform.right))
        {
            Speed = 0;
        }
        else
        {
            Speed = _originalSpeed;
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question