Unity RigidBody2D Hovering not working some computer - c#

Hello i make 2D Game and implemented hover effect(floating).
first my rigidbody2D component option is blew picture.
and I made the hover function work by pressing and holding the X button.
Below is the source I created.
void Update()
{
CheckJump();
CheckRavitate();
DoingAction();
}
void DoingAction()
{
if (this.IsStatus(CustomCharacterInfo.CHAR_STATUS.JUMP))
{
// Jump
this.rigid2D.AddForce(transform.up * JUMP_FORCE);
nowStatus &= ~CustomCharacterInfo.CHAR_STATUS.JUMP;
}
if (IsStatus(CustomCharacterInfo.CHAR_STATUS.RAVITATE))
{
RaycastHit2D rayHitData = Physics2D.Raycast(
new Vector2(transform.position.x, transform.position.y),
new Vector2(0, -1.0f),0.5f,
1 << GlobalLayerMask.TERRIAN_MASK);
bool canRavitate = rayHitData.collider ? false : true;
Debug.DrawRay(transform.position, new Vector2(0, -0.8f),Color.green);
if (canRavitate)
{
float yVel = Physics.gravity.y;
Debug.Log("Ravitae FORECE " + yVel);
//Howering
rigid2D.AddForce(new Vector2(0, -yVel), ForceMode2D.Force);
}
}
}
/*
My intention is that when the x key is pressed for more than 0.05 seconds,
the floating flag is turned on.
When you release x, it will be off.
*/
void CheckRavitate()
{
if (true)
{
if (Input.GetKey(KeyCode.X))
{
if (raviValue.canRavitate && Time.time - raviValue.tDown > 0.05f && rigid2D.velocity.y < 0.2f)
{
Debug.Log("RAVITATE FLAG ON");
nowStatus |= CustomCharacterInfo.CHAR_STATUS.RAVITATE;
rigid2D.velocity = new Vector2(0.0f, 0.0f);
raviValue.canRavitate = false;
}
}
if (this.IsStatus(CustomCharacterInfo.CHAR_STATUS.RAVITATE) && Input.GetKeyUp(KeyCode.X))
{
nowStatus &= ~CustomCharacterInfo.CHAR_STATUS.RAVITATE;
raviValue.canRavitate = true;
}
}
}
void CheckJump()
{
// Jump Function
if (Input.GetKeyDown(KeyCode.X) && jumpcount > 0)
{
isGrounded = false;
nowStatus |= CustomCharacterInfo.CHAR_STATUS.JUMP;
jumpcount--;
raviValue.tDown = Time.time;
}
}
public class RavitateFlag
{
public float tDown;
public bool canRavitate;
public RavitateFlag()
{
tDown = Time.time;
canRavitate = true;
}
}
that result below that
that was errormotion capture
that was correct motion capture
The issue does not floating work with the player's computer.
I do not know why this is the difference. The code is the same and the log is the same too.
If you change one gravitiscale to 1, floating function works normally.
But I think that this is not a solution. Also, when you change the gravity scale to 1, the character that was in normal operation will fly to the sky.
I guess it is time to call the update function, but this is also not clear.

Related

Unity C# Not taking in certain Input

I am creating a FPS game, my player has abilities and her ultimate is Jett's ultimate from Valorant (Her weapon switches to 5 knives that she can throw at enemies) I've managed to make the weapon switch to the knives but when I press the Mouse Left-Click nothing happens. I disabled the script that controls the gun so that the player does shoot bullets, have muzzle flash etc but whether its enabled or disabled the knives don't work. I added debug logs and they arent being called, I use the same button to shoot the gun as throwing the knife. I have also tested it without the 'readyToThrow' variable and 'totalThrows' variable.
Update Method:
void Update()
{
if (Time.time >= QabilityTimer && Input.GetKeyDown(KeyCode.Q))
{
Dash();
QabilityTimer = Time.time + Qcooldown;
}
if (Time.time >= EabilityTimer && Input.GetKeyDown(KeyCode.E))
{
SpeedBoost();
EabilityTimer = Time.time + Ecooldown;
}
if (meterButton.currentProgress == meterButton.maxProgress)
{
ultReady = true;
// Debug.Log("ult ready");
if (Input.GetKeyDown(KeyCode.X))
{
//disable the gun script whilst ult is active.
GameObject gun = GameObject.Find("Guns");
gun.GetComponent<Guns>().enabled = false;
weaponSelection.EunhaUltKnife();
EunhaUltimate();
}
}
if (ultActive)
{
ultTimer -= Time.deltaTime;
}
if (ultTimer <= 0)
{
ResetUltimate();
}
}
Ultimate Method:
public void EunhaUltimate()
{
ultActive = true;
if (Input.GetKeyDown(KeyCode.Mouse0) && readyToThrow && totalThrows > 0)
{
Debug.Log("working");
readyToThrow = false;
GameObject projectile = Instantiate(objectToThrow, attackPoint.position, cam.rotation);
Rigidbody projectileRB = projectile.GetComponent<Rigidbody>();
Vector3 forceToAdd = cam.transform.forward * throwForce + transform.up * throwUpwardForce;
projectileRB.AddForce(forceToAdd, ForceMode.Impulse);
totalThrows--;
Invoke(nameof(ReserThrow), throwCooldown);
}
}
Looks like you can only get into the EunhaUltimate() if you're holding down X:
if (meterButton.currentProgress == meterButton.maxProgress)
{
ultReady = true;
// Debug.Log("ult ready");
if (Input.GetKeyDown(KeyCode.X))
{
//disable the gun script whilst ult is active.
GameObject gun = GameObject.Find("Guns");
gun.GetComponent<Guns>().enabled = false;
weaponSelection.EunhaUltKnife();
EunhaUltimate();
}
}
Try moving the call to EunhaUltimate() outside of that IF statement. You'll need to have a trigger to show when you've pushed X to trigger the ultimate, but it looks like you're currently doing that inside EunhaUltimate(), with the ultActive = true; line.
Other than setting ultActive = true;, all your EunhaUltimate() seems to do is to check the keyboard press, so I'd recommend rewriting your first snippet as follows:
void Update()
{
if (Time.time >= QabilityTimer && Input.GetKeyDown(KeyCode.Q))
{
Dash();
QabilityTimer = Time.time + Qcooldown;
}
if (Time.time >= EabilityTimer && Input.GetKeyDown(KeyCode.E))
{
SpeedBoost();
EabilityTimer = Time.time + Ecooldown;
}
if (meterButton.currentProgress == meterButton.maxProgress)
{
ultReady = true;
// Debug.Log("ult ready");
if (Input.GetKeyDown(KeyCode.X))
{
//disable the gun script whilst ult is active.
GameObject gun = GameObject.Find("Guns");
gun.GetComponent<Guns>().enabled = false;
weaponSelection.EunhaUltKnife();
ultActive = true; // <--- This is a change
}
}
if (ultActive)
{
EunhaUltimate(); // <-- this is a change
ultTimer -= Time.deltaTime;
}
if (ultTimer <= 0)
{
ResetUltimate();
}
}
Try using Input.GetKey(KeyCode.Mouse0) or Input.GetKeyUp(KeyCode.Mouse0) instead Input.GetKeyDown(KeyCode.Mouse0).

WaitForSecondsRealtime not working as expected

So decided to give game dev a try, picked up unity,Now I decided to create a simple ping pong game.
My game has Bat.cs class, ball.cs, and GameHandler.cs.
The GameHandler.cs initializes the batRight, batLeft, ball using the Bat.cs, Ball.cs class and prefabs, it also keeps track of if someone scores then starts a serve by stopping the rally:
public class GameHandler : MonoBehaviour
{
public Bat bat;
public Ball ball;
public Score score;
public static Vector2 bottomLeft;
public static Vector2 topRight;
public static bool rallyOn = false;
public static bool isServingLeft = true;
public static bool isServingRight = false;
public static bool isTwoPlayers = true;
static Bat batRight;
static Bat batLeft;
public static Ball ball1;
static Score scoreLeft;
static Score scoreRight;
// Start is called before the first frame update
void Start()
{
//Convert screens pixels coordinate into games coordinate
bottomLeft = Camera.main.ScreenToWorldPoint(new Vector2(0, 0));
topRight = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height));
ball1 = Instantiate(ball) as Ball;
//Debug.Log("GameHandler.Start");
batRight = Instantiate(bat) as Bat;
batRight.Init(true);
batLeft = Instantiate(bat) as Bat;
batLeft.Init(false);
ball1.transform.position = new Vector3(batLeft.transform.position.x + ball1.getRadius() * 2, batLeft.transform.position.y);
//Instatiate scores
scoreLeft = Instantiate(score, new Vector2(-2, -4), Quaternion.identity) as Score;
scoreRight = Instantiate(score, new Vector2(2, -4), Quaternion.identity) as Score;
}
private void Update()
{
if (isServingLeft)
{
ball1.transform.position = new Vector3(batLeft.transform.position.x + ball1.getRadius() * 2, batLeft.transform.position.y);
if (Input.GetKey(KeyCode.LeftControl))
{
rallyOn = true;
isServingLeft = false;
}
}
if (isServingRight)
{
ball1.transform.position = new Vector3(batRight.transform.position.x - ball1.getRadius() * 2, batRight.transform.position.y);
if (isTwoPlayers && Input.GetKey(KeyCode.RightControl))
{
rallyOn = true;
isServingRight = false;
}
else
{
StartCoroutine(batRight.serveAi());
if (GameHandler.rallyOn)
{
StopCoroutine(batRight.serveAi());
}
}
}
}
public static void increaseScoreByOne(bool isRight)
{
rallyOn = false;
if (isRight)
{
scoreRight.increaseScore();
isServingRight = true;
}
else
{
scoreLeft.increaseScore();
isServingLeft = true;
}
}
}
The ball.cs listens to the static GameHandler.rallyOn and starts moving the ball accordingly, it also changes direction of the ball if it hits a vertical wall or the bat:
public class Ball : MonoBehaviour
{
[SerializeField]
float speed;
float radius;
public Vector2 direction;
public Vector3 ballPosition;
// Start is called before the first frame update
void Start()
{
direction = Vector2.one.normalized; // direction is (1, 1) normalized
//Debug.Log("direction * speed * Time.deltaTime:" + direction * speed * Time.deltaTime);
radius = transform.localScale.x / 2;
}
// Update is called once per frame
void Update()
{
ballPosition = transform.position;
if (GameHandler.rallyOn)
{
startRally();
}
}
void startRally()
{
transform.Translate(direction * speed * Time.deltaTime);
Debug.Log("direction * speed * Time.deltaTime:" + direction * speed * Time.deltaTime);
if ((transform.position.y + radius) > GameHandler.topRight.y && direction.y > 0)
{
direction.y = -direction.y;
}
if ((transform.position.y + radius) < GameHandler.bottomLeft.y && direction.y < 0)
{
direction.y = -direction.y;
}
if ((transform.position.x + radius) > GameHandler.topRight.x && direction.x > 0)
{
// Left player scores
GameHandler.increaseScoreByOne(false);
//For no, just freeza the script
// Time.timeScale = 0;
//enabled = false;
}
if ((transform.position.x - radius) < GameHandler.bottomLeft.x && direction.x < 0)
{
// right player scores
GameHandler.increaseScoreByOne(true);
}
}
void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Bat")
{
if (collision.GetComponent<Bat>().isRight && direction.x > 0)
{
direction.x = -direction.x;
}
if (!collision.GetComponent<Bat>().isRight && direction.x < 0)
{
direction.x = -direction.x;
}
}
}
public float getRadius()
{
return radius;
}
}
The bat.cs initiazes the two paddles, and either listens to user input if its 2 players or listens to player and use AI if it is player vs CPU.:
public class Bat : MonoBehaviour
{
float height;
[SerializeField] // this make this appear on editor without making this field public
float speed;
string input;
public bool isRight;
string PLAYER1_INPUT = "PaddleLeft";
string PLAYER2_INPUT = "PaddleRight";
// Start is called before the first frame update
void Start()
{
height = transform.localScale.y;
}
// Update is called once per frame
void Update()
{
if (GameHandler.isTwoPlayers)
{
if (isRight)
{
movePaddleonUserInput(PLAYER2_INPUT);
}
else
{
movePaddleonUserInput(PLAYER1_INPUT);
}
}
else
{
if (isRight)
{
movePaddleAi();
}
else
{
movePaddleonUserInput(PLAYER1_INPUT);
}
}
}
void movePaddleAi()
{
if (isRight && GameHandler.ball1.direction.x > 0 && GameHandler.ball1.ballPosition.x > 0)
{
//transform.Translate(direction * speed * Time.deltaTime);
if ((transform.position.y) > GameHandler.ball1.ballPosition.y && GameHandler.ball1.direction.y < 0)
{
transform.Translate(GameHandler.ball1.direction * speed * Time.deltaTime * Vector2.up);
}
if ((transform.position.y) < GameHandler.ball1.ballPosition.y && GameHandler.ball1.direction.y > 0)
{
transform.Translate(GameHandler.ball1.direction * speed * Time.deltaTime * Vector2.up);
}
}
}
void movePaddleonUserInput(string input)
{
// move = (-1 -> 1) * speed * timeDelta(this keep move framerate independent)
float move = Input.GetAxis(input) * speed * Time.deltaTime;
//Debug.Log((transform.position.y + height / 2) + " > "+ GameHandler.topRight.y+ "&&" + move +" > 0");
//Restrict paddle movement to to the screen
// (top edge of paddle > Screen top and we are moving up)
if ((transform.position.y + height / 2) > GameHandler.topRight.y && move > 0)
{
move = 0;
}
// (bottom edge of paddle < Screen top and we are moving down)
if ((transform.position.y - height / 2) < GameHandler.bottomLeft.y && move < 0)
{
move = 0;
}
transform.Translate(move * Vector2.up);
}
public void Init(bool isRightPaddle)
{
isRight = isRightPaddle;
Vector2 pos;
if (isRightPaddle)
{
isRight = isRightPaddle;
pos = new Vector2(GameHandler.topRight.x, 0);
// offset since center is the anchor
pos -= Vector2.right * transform.localScale.x;
input = "PaddleRight";
}
else
{
pos = new Vector2(GameHandler.bottomLeft.x, 0);
// offset since center is the anchor
pos += Vector2.right * transform.localScale.x;
input = "PaddleLeft";
}
transform.name = input;
transform.position = pos;
}
public IEnumerator serveAi()
{
yield return new WaitForSecondsRealtime (2f);
GameHandler.rallyOn = true;
GameHandler.isServingRight = false;
}
}
Now I also have score.cs and mainMenu scene , but no need to include that for this question, What I am struggling with now is the AI not stopping after it scores a point, I want the AI paddle to stop for a few seconds before it serves.
As you can see in the code, I added a yield return new WaitForSecondsRealtime(2f);
public IEnumerator serveAi()
{
yield return new WaitForSecondsRealtime (2f);
GameHandler.rallyOn = true;
GameHandler.isServingRight = false;
}
But this only cause the paddle to wait for the first time it scores , and then if it scores again in quick interval, it doesn't wait at all.
Not sure what I doing wrong here, thanks for your time.
The more plausible explanation to me would be that GameHandler.rallyOn and isServing* aren't all being reset to the correct values to prevent the serve from occurring before the coroutine even begins, or another check is needed somewhere to prevent a serve from occurring if all of the correct booleans aren't set. Try placing appropriate breakpoints and stepping through in a debugger.
You'd probably be better off using WaitForSeconds rather than WaitForSecondsRealtime, by the way, at least if there's a chance you might want to allow the game to be paused in the future.
Realized that the coroutine is called multiple times even before its finished due do it being called from update function in GameHandler.cs. Needed a way to check if the co-routine is already running and not start a new one from update if so, used the Game.isServing variable to do so:
public IEnumerator serveAi()
{
GameHandler.isServingRight = false; // coroutine started , no need to start new one
yield return new WaitForSecondsRealtime (2f);
GameHandler.rallyOn = true;
}
And my update in GameHandler is already checking for that variable before starting the coroutine:
private void Update()
{
if (isServingLeft)
{
ball1.transform.position = new Vector3(batLeft.transform.position.x + ball1.getRadius() * 2, batLeft.transform.position.y);
if (Input.GetKey(KeyCode.LeftControl))
{
rallyOn = true;
isServingLeft = false;
}
}
if (isServingRight)
{
ball1.transform.position = new Vector3(batRight.transform.position.x - ball1.getRadius() * 2, batRight.transform.position.y);
if (isTwoPlayers && Input.GetKey(KeyCode.RightControl))
{
rallyOn = true;
isServingRight = false;
}
else
{
StartCoroutine(batRight.serveAi());
}
}
}

My rb2d gravity scale is set to 0 yet I still fall when I press the down arrow on my ladder

I'm making a ladder for my Unity game. Nothing much happens when you hover over it (that's normal). I want to freeze gravity by setting gravityscale 0 whenever the up arrow key is pressed (or w). Thankfully that works. Unfortunately though whenever I go down, gravity is still 0 but somehow my character falls back to the ground.
Here's my player code. Sorry the formatting is very bad; I just deleted the things that didn't have to do with ladders so you won't read irrelevant details.
// ladder
public float climb;
public float climbspeed;
public float gravitystore;
public bool laddered;
public GameObject laddercheck;
public float upaxis;
public xpositionladdercheck ladderx;
// Start is called before the first frame update
void Start()
{
ladderx = FindObjectOfType<xpositionladdercheck>();
jumptimecounter = Jumptime;
jumpscriptbetter = FindObjectOfType<BetterJump>();
gameover = false;
respawnscreen = FindObjectOfType<RespawnIntermission>();
lives = 5;
atkindex = FindObjectOfType<attackindex>();
scale =transform.localScale;
basicattackscript = FindObjectOfType<BasicAttack>();
basicattacksupply = 0;
rb = GetComponent<Rigidbody2D>();
gravitystore = rb.gravityScale;
}
// Update is called once per frame
private void Update()
{
horimove = Input.GetAxis("Horizontal");
if (isDead == false)
{
upaxis = Input.GetAxis("Vertical");
anim.SetFloat("run", Mathf.Abs(horimove));
if (Input.GetKeyDown(KeyCode.Space) && laddered)
{
jumpladder();
}
anim.SetFloat("run", Mathf.Abs(horimove));
if (laddered && Mathf.Abs(upaxis) > .01)
{
rb.gravityScale = 0;
climbm();
} else if (!laddered)
{
rb.gravityScale = gravitystore;
}
if (laddered&&Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine("jumpable");
}
rb.velocity = new Vector2(speed * horimove * Time.fixedDeltaTime, rb.velocity.y);
if (Input.GetKey(KeyCode.Space) && OnGround)
{
jump();
}
}
}
IEnumerator jumpable()
{
laddercheck.SetActive(false);
yield return new WaitForSeconds(.8f);
laddercheck.SetActive(true);
}
void climbm()
{
if (laddered)
{
if (upaxis > .1f) {
} else if (!laddered)
{
rb.constraints = RigidbodyConstraints2D.FreezeRotation;
}
rb.velocity = Vector2.up * climbspeed * upaxis *Time.deltaTime;
transform.position = new Vector2(ladderx.ladderxpos, rb.position.y);
// the ladder.x things is just a script that gets the x position of the ladder but it works well so ignore that.
}
}
public void jump()
{
}public void jumpladder()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector2.up * jumpforce * Time.fixedDeltaTime);
}
}
}
}
I set mass to the lowest (.0001) and still the same thing happens. I didn't include the ladderx position script or the sensing that I'm even on a ladder script but that's irrelevant to the question. It senses everything just fine and the xposition script works well as well.
I figured it out. For some reason I had to set the Physics2D.gravity to new Vector2 (0,0); whenever I climb the ladder. Then I made a vector 2 physgravity variable that stores the natural gravity and set it back to that whenever I leave the ladder.
public Vector2 physgravity;
physgravity = Physics2D.gravity;
Physics2D.gravity = new Vector2(0f, -9.81f);
private void Update()
{
if (!laddered)
{
Physics2D.gravity = new Vector2(0f, -9.81f);
}
____________________ (later on in the script)
if (laddered && Mathf.Abs(upaxis) > .01)
{
rb.gravityScale = 0;
Physics2D.gravity = new Vector2(0, 0);
rb.velocity = new Vector2(0, 0);
climbm();

Enemy AI not working properly with NavMesh

I been trying to create an AI for the enemy to patrol between some points and, when spot player in a certain range, the enemy stop the patrol and follows the player.
The thing is, if I only have the enemy to follow the player, works perfectly the same happens with just the patrol, but both together doesn't seem to work. The enemy acts in a weird way.
My code:
public void Start()
{
_navMeshAgent = this.GetComponent<NavMeshAgent>();
anim = GetComponent<Animator>();
if (_navMeshAgent == null)
{
Debug.LogError("not attached to " + gameObject.name);
}
else
{
if (_patrolPoints != null && _patrolPoints.Count >= 2)
{
_currentPatrolIndex = 0;
anim.SetBool("idle", true);
SetDestination();
}
else
{
Debug.Log("Insufficient patrol points.");
}
}
}
void Update()
{
if (player == null)
{
player = GameObject.Find("Player Character").GetComponent<Transform>();
}
if (Vector3.Distance(player.transform.position, this.transform.position) < 10)
{
chacePlayer();
}
else
{
patrol();
}
bool patrol()
{
Debug.Log("patrolling");
//Check if we're close to the destination.
if (_travelling && _navMeshAgent.remainingDistance <= 1.0f)
{
_travelling = false;
anim.SetBool("idle", false);
anim.SetBool("move", true);
//If we're going to wait, then wait dumbass!
if (_patrolWaiting)
{
_waiting = true;
_waitTimer = 0f;
anim.SetBool("idle", true);
anim.SetBool("move", false);
}
else
{
ChangePatrolPoint();
SetDestination();
}
}
//Instead if we're waiting...
if (_waiting)
{
_waitTimer += Time.deltaTime;
if (_waitTimer >= _totalWaitingTime)
{
_waiting = false;
anim.SetBool("move", true);
anim.SetBool("idle", false);
ChangePatrolPoint();
SetDestination();
}
}
return true;
}
}
private void SetDestination()
{
if (_patrolPoints != null)
{
Vector3 targetVector = _patrolPoints[_currentPatrolIndex].transform.position;
_navMeshAgent.SetDestination(targetVector);
_travelling = true;
////anim.SetBool("idle", false);
////anim.SetBool("move", true);
}
}
//Selects a new patrol point in the available list, but
//also with a small probability allows for us to move forward or backwards.
private void ChangePatrolPoint()
{
//Unity generate random number between 0 and 1
if (UnityEngine.Random.Range(0f, 1f) <= _switchProbability)
{
//decides if go forward or backwards: whatever the value, make the oposite
_patrolForward = !_patrolForward;
}
if (_patrolForward)
{
//if the patrolpoint exceedes patrolpoints.count, go backs to zero
_currentPatrolIndex = (_currentPatrolIndex + 1) % _patrolPoints.Count;
}
else
{
if (--_currentPatrolIndex < 0)
{
_currentPatrolIndex = _patrolPoints.Count - 1;
}
}
}
void chacePlayer()
{
Vector3 direction = player.transform.position - this.transform.position;
this.transform.rotation = Quaternion.Slerp(this.transform.rotation,
Quaternion.LookRotation(direction), 0.1f);
direction.y = 0;
if (direction.magnitude > 2)
{
this.transform.Translate(0, 0, 0.05f);
Debug.Log("chacing");
}
}
At first I thought it was because the code was running both together so I put a Debug to see if it was that, but the debug of the patrol stops every time the enemy is following the player.
Can someone please help me?

How to prevent any player Input if the object is moving

I am creating a clone of Billiards and I cannot work out how to stop the player from interacting with and launching the ball while it is still moving; below is my attempt. I have placed an if statement that checks whether the ball is moving on both the mouseDrag and mouseUp functions. I have also tried using isSleeping() but this caused the ball to not move at all.
If possible I would like to apply this method to all of the balls and not just the cue ball; so that all balls have to have stopped before any actions may happen. This is currently in my "player" script, if I should move it a GameManager script please let me know.
private void Update()
{
speed = rb.velocity.magnitude;
if (speed < 0.5)
{
rb.velocity = new Vector3(0, 0, 0);
}
}
void OnMouseDrag()
{
if (speed == 0)
{
mousePointB.GetComponent<SpriteRenderer>().enabled = true;
currDistance = Vector3.Distance(mousePointA.transform.position, transform.position);
if (currDistance <= 3f)
{
spaceLimit = currDistance;
}
else
{
spaceLimit = maxDistance;
}
shootPower = Mathf.Abs(spaceLimit) * shootPowervar;
Vector3 dimxy = mousePointA.transform.position - transform.position;
float difference = dimxy.magnitude;
mousePointB.transform.position = transform.position + ((dimxy / difference) * currDistance * -1);
mousePointB.transform.position = new Vector3(mousePointB.transform.position.x, mousePointB.transform.position.y, -0.8f);
shootDirection = Vector3.Normalize(mousePointA.transform.position - transform.position);
}
else
{
}
}
void OnMouseUp()
{
if (speed == 0)
{
mousePointB.GetComponent<SpriteRenderer>().enabled = false;
arrow.GetComponent<SpriteRenderer>().enabled = false;
circle.GetComponent<SpriteRenderer>().enabled = false;
Vector3 push = shootDirection * shootPower * -1;
GetComponent<Rigidbody2D>().AddForce(push, ForceMode2D.Impulse);
}
else
{
}
}
if your test speed == 0 is not functional, you could record the last position of the ball, and set a boolean isMoving = true, if actual position of ball is different thant the last, then record the lastposition and so on
Vector3 LastPosition;
bool isMoving;
void Update()
{
isMoving = BallPosition == LastPosition;
:
:
}
void OnMOuseDrag()
{
if(!isMoving) return;
}
void OnMOuseUp()
{
if(!isMoving) return;
}

Categories

Resources