Add force from touch position to the center of the object

So I’m making this game cloning the facebook football mobile game. I could barely make the ball bounce whenever I touch it, but I couldn’t figure a way to make it go left and right if you touch the ball from the opposite direction. I was thinking like the post suggests about a way to apply a force from the position touched to the position of the ball.

using UnityEngine;
using System.Collections;

public class Touch : MonoBehaviour {


	// Update is called once per frame
	void Update () 
	{

		if (Input.GetMouseButtonDown (0)) 
		{
			Debug.Log ("Clicked");
			Vector2 pos = new Vector2 (Input.mousePosition.x, Input.mousePosition.y);
			RaycastHit2D hitInfo = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (pos), Vector2.zero);
			// RaycastHit2D can be either true or null, but has an implicit conversion to bool, so we can use it like this
			if (hitInfo) 
			{
				Debug.Log (hitInfo.transform.gameObject.name);
				// Here you can check hitInfo to see which collider has been hit, and act appropriately.
				hitInfo.rigidbody.AddForce(new Vector2( 0, 300));
			}
		}
	}
}

1 Answer

1

This should do what you explained if I understood you well. It shows how to get a direction from 2 Vectors so hopefully you’ll find it useful. Code should be placed on the ball. In inspector settings for rigidbody2d set Linear drag higher then 0 (otherwise it will keep going forever) if it is a top down game Gravity to 0.

	Rigidbody2D rb;
	public float strenght = 100;

	// Use this for initialization
	void Start () 
	{
		rb = GetComponent<Rigidbody2D>();
	}
	
	// Update is called once per frame
	void Update () 
	{

		if (Input.GetMouseButtonDown(0)) 
		{
			Vector2 forceOrigin = Camera.main.ScreenToWorldPoint (Input.mousePosition);
			Vector2 ballPos = transform.position; //ball transform
			Vector2 direction = Vector3.Normalize (ballPos - forceOrigin); //Get Vector direction
			
			rb.AddForce (direction * strenght);
		}

	}

What doesn't work? What happens? This shouldn't affect looking around at all. What was the code you used to implement my solution? I also don't understand "just want the player to move forward and ... in any other direction" - If that's what you're asking about, where does sliding come in? To be clear, you want the character to only be able to slide in the direction they are moving? Or only towards positive x? What type of game is this? What axes does your character move along?