- Home /
Add force based on transform position x value
Hey there fellow unity artists. I am very new to coding and i want to find a solution to my problem. I want to create 2D juggling game which is i need only foot(GameObject with boxcollider2d and moves up and go back on getkeydown) animation and add force based on the value of the transform y position in order to give the ball ascending variation and more fun gameplay. My code is not variating it very well. What should i do to make it work.
using UnityEngine;
using System.Collections;
public class KickForce : MonoBehaviour
{
public float forceScale;
//adding force to the ball
void OnCollisionEnter2D (Collision2D col)
{
Debug.Log("Collision!");
if (col.gameObject.tag == "ball")
{
col.gameObject.GetComponent<Rigidbody2D>().AddForce(transform.up * 600 * forceScale,ForceMode2D.Force);
}
}
//getting the transform.x value from the collider to use it as a force scale
void FixedUpdate ()
{
forceScale = gameObject.transform.position.y;
}
}
(1) are you sure position.y varies enough that it has an effect? If it doesn't you may need to add both an extra factor (or change 600) and add a base force.
(2) Also, why don't you just change the forceScale in OnCollisionEnter2D ins$$anonymous$$d of in FixedUpdate? Is that for debugging purposes?
(3) Just a tip. Try to use col.CompareTag("ball")
ins$$anonymous$$d of tag == "ball"
. It's slightly faster and involves less typing.
Am so sorri man. im very new to coding. Thanks for help
I i changed forceScale to oncollisionenter2d. its not working properly, also changed tag == "ball"
to col.CompareTag("ball")
ball not functions normal anymore. T_T
Your answer
![](https://koobas.hobune.stream/wayback/20220612035845im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Adding rotation to Physics.AddForce(); ... Getting weird error? 0 Answers
Add force on the ball based in Mouse Drag 0 Answers
Deteriorating force on object? 0 Answers