- Home /
How do I add ForceMode.VelocityChange to this code
How do I add ForceMode.VelocityChange to this code, I made a code that moves the player right or left depending on the side of screen u touch on the phone, but when I touch the player continues going and not stoping so here is the code I want ForceMode.VelocityChange to add to @Brackeys
public class Touchcon : MonoBehaviour {
public float touchspeed= 300f;
public GameObject player;
private Rigidbody Rb;
private float ScreenWidth;
// Start is called before the first frame update
void Start()
{
ScreenWidth = Screen.width;
Rb = player.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
int i = 0;
while (i < Input.touchCount)
{
if (Input.GetTouch(i).position.x > ScreenWidth / 2)
{
RunPlayer(1.0f);
}
if (Input.GetTouch(i).position.x < ScreenWidth / 2)
{
RunPlayer(-1.0f);
}
++i;
}
}
private void FixedUpdate()
{
#if UNITY_EDITOR
RunPlayer(Input.GetAxis("Horizontal"));
#endif
}
private void RunPlayer(float honrizontalInput)
{
Rb.AddForce(new Vector3(honrizontalInput * touchspeed * Time.deltaTime, 0 ));
}
Answer by I_Am_Err00r · Sep 20, 2019 at 03:49 PM
I don't have an IDE to test this out with, but I think I see what is going on, let me know if this helps:
void Update()
{
if(Input.touchCount > 0
{
Touch touch = Input.GetTouch(0)
if (Input.GetTouch(0).position.x > ScreenWidth / 2)
{
RunPlayer(1.0f);
}
if (Input.GetTouch(0).position.x < ScreenWidth / 2)
{
RunPlayer(-1.0f);
}
}
}
I don't know if you have other commands that would be called if you had multiple fingers on the screen, but I believe this will run the code you are trying to only if you are actually touching the screen, regardless of how many fingers that is.
If it doesn't work, let me know, I can take another stab at it in about an hour when I have access to Unity and an IDE.
@I_Am_Err00r So if I add this to my code, then my player will cease to have momentum when they move left or right? $$anonymous$$eaning, they wont keep going right or left while Im trying go to the opposite direction?