The problem is simple but I am new to unity.
I want to add a force when click the object. Like a kick.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class box : MonoBehaviour
{
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if(Input.GetMouseButtonDown(0))
{
rb.AddForce(Vector2.up * 17f, ForceMode2D.Impulse);
}
}
}
But it doesn't work because it just add a generic force.
This question is unclear, you need to provide more information, but if you want to implement a "kick" like force (I guess like in soccer) then you should calculate the direction from which you are kicking the ball from
I suggest something like this -
rb.AddForce(_kickDirection * _kickForce, ForceMode2D.Impulse)
kickDirection is where you desire to kick towards.
You code works fine. Just be sure that you have your box, and Rigidbody2D componenets attached to your gameobject, like this:
Its not when you click the object, but wherever you click according to your code. If this is not what you wanted you need to explain your question better.
Edit:
To provide a "kick force" you need to know where the click hit. Find some code for that:
public class click : MonoBehaviour {
void Update() {
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Debug.DrawRay(ray.origin, ray.direction * 20, Color.white);
if (Physics.Raycast(ray, out hit)){
if (hit.collider != null) {
Debug.Log("hit!");
}
else {
Debug.Log("no hit");
}
}
}
}
}
You need to be sure your target has a collider component. With hit.point you can get the position. Check the docs.
Once you have the hit position, you can define which direction you want to apply the force in. For the kick force example can be de direction opposite to the one from the center of your box to the hit point: Vector3 forceDir = boxTransform.position - hit.point;