[HELP] [2D] Launch an object in a particular direction

So, I’m making a game (for touchscreen) for my college project. In this project, I want to launch a ball in the direction where user want’s it to.

[What currently do I have?]:

if (Input.GetMouseButtonDown(0)){
		hasStarted = true;
		print ("Left Mouse button clicked");
		this.GetComponent<Rigidbody2D>().velocity = new Vector2 (2f,7.5f);
}

74087-capture.png

[Behavior I need]:

  • Ball should have a ray emerging from it in upward direction, the user should be able to move this ray between 10’o clock and 2’o clock.
  • After the user has acquired the direction he wants to point, he may tap on the screen to launch the ball (or maybe a button maybe used to launch the ball).

Can you please help me out with this?

So, I found the answer myself :smiley:

  1. For creating a ray, Just go here and copy down the script he has shown in the video ( Just remove the if (counter > dist) condition )

Link : Animate a line draw using Line Renderer Component - YouTube

Let pointA be the ball, and pointB be an empty gameObject in the heirarchy. To move the ray, just move the pointB left or right, below is a script that I attached to pointB for moving it.

public float speed = 15.0f;
	public float padding = 1.0f;

	float xmin;
	float xmax;
	// Use this for initialization
	void Start () {
		float distance = transform.position.z - Camera.main.transform.position.z;
		Vector3 leftmost = Camera.main.ViewportToWorldPoint(new Vector3(0,0,distance));
		Vector3 rightmost = Camera.main.ViewportToWorldPoint(new Vector3(1,0,distance));
		xmin = leftmost.x + padding;
		xmax = rightmost.x - padding;
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetKey(KeyCode.LeftArrow)){
			transform.position += Vector3.left * speed * Time.deltaTime;
			}
		if (Input.GetKey(KeyCode.RightArrow)){
			transform.position += Vector3.right * speed * Time.deltaTime;
			}
		float newX = Mathf.Clamp (transform.position.x, xmin, xmax);
		transform.position = new Vector3 (newX, transform.position.y, transform.position.z);
	}

I didn’t had laser material, so I used flame material given in the standard assets of Unity 5.3.5f. And make the ray inActive after launching the ball.
74171-c2.png

  1. To launch the ball in particular direction go here, Fire a Projectile towards a specific object? - Questions & Answers - Unity Discussions

Just instead of clone.velocity, use this.GetComponent<Rigidbody2D>().velocity

I used

this.GetComponent<Rigidbody2D>().velocity = (ptB.transform.position - transform.position).normalized * speed;