Home > Blockchain >  Conflicting IF statements in Unity C# , Soccer Game
Conflicting IF statements in Unity C# , Soccer Game

Time:11-03

I am a starter in Unity and developing a soccer game. I have a problem ,my IF statements conflict each other. Let me explain it in detail. In order for a ball to stick to player, I have used IF operator, so whenever the distance between the player and the ball is less than < 0.5 , the ball sticks to player and move together with it. Now when I try to set up shooting the ball (I try with "addforce") it doesnt let me, cause the ball is still attached to player and distance is <0.5.

This one is the balls script.

public bool sticktoplayer;
public transform player; 
//gameobject Player is attached
float distancetoplayer;
Rigidbody rb; 
//balls rigidbody

void Awake ()
{
rb = getComponent<Rigidbody>();
}

void Update()
{
If (!sticktoplayer)
{
float distancetoplayer = Vector3.Distance (player.position, transform.position);
if(distancetoplayer < 0.5f)
{
sticktoplayer = true;
}
}
else
{
transform.position = player.position;
}

if(Input.GetKeyDown(KeyCode.Space))


{
rb.addforce(20, 0, 0, ForceMode.Impulse);
sticktoplayer = false;
}

When the player is not controlling the ball the force is succesfully applied to the ball, but when the ball is attached (distancetoplayer<0.5) then the other IF statements blocks it from shooting. Maybe there are some work arounds ? Thanks.

I tried to make another if statement.

CodePudding user response:

why dont you try sticking the ball to the player by collision? instead of checking the distance, create a collider with the radius or scale you desire and whenever the ball is inside the collider (when it triggers with the collider) stick it to the player. Because you will not be able to let the ball go since the ball will always be less then 0.5f away from the player once it sticks

CodePudding user response:

have you tried it this way?

if(Input.GetKeyDown(KeyCode.Space))
{
 sticktoplayer = false;
 rb.addforce(20, 0, 0, ForceMode.Impulse);
}
  •  Tags:  
  • c#
  • Related