I am working on pong, and depend on different parts of the paddle it hits, different directions it will go. I am going to use integers, but for now im just going to a Boolean to test the x axis movement. depends on if d is true or not, it will go left or right. for some reason, it always does what ever the if statement says, and nothing what the else statement says(even if the if statement is false). i tried switching statements, but that doesn’t work.
using UnityEngine;
using System.Collections;
public class BallMovement : MonoBehaviour {
public float x;
public float y;
public bool d = false;
Transform tf;
void Start () {
tf = GetComponent<Transform>();
}
void Update () {
Move ();
}
void Move(){
if (d == true) {//i also tried just "if (d)", but still the same movement
x = x + 0.1f;
} else {
x = x - 0.1f;
}
Vector2 v = new Vector2 (x,y);
tf.position = v;
}
}
Your d Boolean is public, which means other sources can modify it, perhaps the editor is overriding its value. In the editor in sidebar at your object under your Ballmovement component, should be a box that indicates if its true or not. Untick this if its ticked. Otherwise, add “d = false;” in the Start method in your scrip to ensure its false
Another thing i want to add, and this is subjective, is that instead of x = x+0.1f, you can also just write x+= 0.1f; this has the same effect, but might be easier to read.
Lastly, you might want to make the speed dependent on your frames per second, so the ball always has the same speed on different matchines. You can do this by writing x+x+speedTime .deltaTime or simply x+=speedTime.deltaTime;
I hope this was somewhat helpful.
Good luck
d is a public variable, so it’s initialised to the value set in the inspector, which I’m guessing is “true”. You never change it otherwise.
If you use public variables, they will be setted in inspector, not in decleration.
You may either want to initialize things on Start() or to hide you public variables from showing up on inspector like this:
[HideInInspector] public float x = 3.0f;
Also take a look at here: http://unity3d.com/support/documentation/ScriptReference/HideInInspector.html
Best wishes.