Libgdx, Intersector.overlaps is not checking when out of focus - android

I am developing a block game. i have two moving blocks in vertical direction. one of the block is also moving horizontally (like auto moving car in ROAD FIGHTER). i am checking the block interaction by Intersector.overlaps but when my block goes out of window (i.e. position becomes less than 0) ,my code of overlaps not working .
if(Intersector.overlaps(block1.getBoundingRectangle(), block2.getBoundingRectangle())){
// do not update values
}else{
// update the values of block1 and block 2
}
public static int[] value={138,195,248,303};
public static boolean[] valueHolder={true,false,false,true};
public void update(float delta) {
velocity.set(0, backgroun.velocity.y-scrollSpeed);
position.add(velocity.cpy().scl(delta));
if(position.y>850){
isScrollableTop=true;
}
selfMove(delta);
if(position.y<-150){
position.y=-150;
}
carBoundingRectangle.setX(position.x);
carBoundingRectangle.setY(position.y);
}
private void changeArray() {
if(position.x>=138 && position.x<167){
if(!GameConstants.valueHolder[0]){
GameConstants.valueHolder[blockNumber]=false;
GameConstants.valueHolder[0]=true;
blockNumber=0;
}
}else if(position.x>=167 && position.x<222 ){
if(!GameConstants.valueHolder[1]){
GameConstants.valueHolder[blockNumber]=false;
GameConstants.valueHolder[1]=true;
blockNumber=1;
}
}else if(position.x>=222 && position.x<275){
if(!GameConstants.valueHolder[2]){
GameConstants.valueHolder[blockNumber]=false;
GameConstants.valueHolder[2]=true;
blockNumber=2;
}
}else if(position.x>=275 ){
if(!GameConstants.valueHolder[3]){
GameConstants.valueHolder[blockNumber]=false;
GameConstants.valueHolder[3]=true;
blockNumber=3;
}
}
}
Thanks in advance

Related

Android Unity Controls

I am trying to convert my PC game code in unity to android and I am stuck on the controls change. Please help!
This is the code:
Getting the state of rocket.
enum State { Dying, Alive, Transcending }
State state = State.Alive;
// Update is called once per frame
void Update()
{
if (state == State.Alive)
{
RespondToThrustInput();
RespondToRotateInput();
}
}
When the rocket collides with anything it checks whether it's friendly or not before changing its state from alive to dead.
private void OnCollisionEnter(Collision collision)
{
if (state != State.Alive) { return; }
switch (collision.gameObject.tag)
{
case "Friendly":
break;
case "Finish":
state = State.Transcending;
audioSource.Stop();
audioSource.PlayOneShot(finishgame);
finishgameParticles.Play();
Invoke("LoadNextScene", levelloaddelay);
break;
default:
state = State.Dying;
audioSource.Stop();
audioSource.PlayOneShot(death);
deathParticles.Play();
Invoke("LoadFirstScene", levelloaddelay);
break;
}
}
private void LoadFirstScene()
{
SceneManager.LoadScene(9);
}
Loading next scene using build index.
private void LoadNextScene()
{
if (nextscenetoload > 7)
{
nextscenetoload = 0;
}
SceneManager.LoadScene(nextscenetoload);
}
Space for ignition or force and audio sources for playing sound effects.
private void RespondToThrustInput()
{
if (Input.GetKey(KeyCode.Space))
{
ApplyThrust();
}
else
{
audioSource.Stop();
mainengineParticles.Stop();
}
}
Apply thrust is the method I wrote with the logic of the rocket thrust.
private void ApplyThrust()
{
rigidbody.AddRelativeForce(Vector3.up * mainThrust * Time.deltaTime);
if (!audioSource.isPlaying)
audioSource.PlayOneShot(mainengine);
mainengineParticles.Play();
}
Rotation of the rocket or Left and right. Here I am trying to rotate the rocket using the A and D keys
void RespondToRotateInput()
{
float rotationThisFrame = rcsThrust * Time.deltaTime;
if (Input.GetKey(KeyCode.A))
{
rigidbody.freezeRotation = true;
transform.Rotate(Vector3.forward * rotationThisFrame);
rigidbody.freezeRotation = false;
}
else if (Input.GetKey(KeyCode.D))
{
rigidbody.freezeRotation = true;
transform.Rotate(-Vector3.forward * rotationThisFrame);
rigidbody.freezeRotation = false;
}
}
For PC games there is a keyboard to use to control, but for the android there are touches, you have to verify if there is a touch on the screen, like this:
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
//do something
}
also you need more work to determine where the touch is located and do you customizations... or in case you're not interested about this input handling, you can use some assets from Unity Assets Store to cover this part for you.
check this link for more information about touch control in Unity documentation:
https://docs.unity3d.com/ScriptReference/Input.GetTouch.html

How to check for tap in monogame?

I want to check that Rectangle was tapped. This mehod does the job and it works almost how I want:
private bool CheckRectangleTouch(Rectangle target)
{
var touchCollection = TouchPanel.GetState();
if (touchCollection.Count > 0)
{
foreach (var touch in touchCollection)
{
if (target.Contains(touch.Position))
{
return true;
}
}
}
return false;
}
Problem I have is that after I've tapped rectangle it keeps returning true until I release it (it can register 10-30 times for one tap) and I want it to return true just once - for the first touch.
I've tried this (replace code inside foreach):
var isFirstTouch = !touch.TryGetPreviousLocation(out _);
if (target.Contains(touch.Position) && isFirstTouch)
{
return true;
}
And this (bad one, I don't really want it to register after release):
if (target.Contains(touch.Position) && touch.State == TouchLocationState.Released)
{
return true;
}
But nothing is does it. Either logic is not consistent or doesn't work at all.
So how do I check for tap?
Update: this works but it's very hacky, has delay and gives me random phantom taps:
try
{
var tap = TouchPanel.ReadGesture(); // falls each time when no input
return tap.GestureType == GestureType.Tap && target.Contains(tap.Position);
}
catch { }
return false;
Here's what I ended up doing:
I have singleton to hold my game state (many different props updated as needed). I added to it:
public TouchCollection TouchCollection { get; set; }
Prop to hold TouchPanel.GetState result. I fill it in Games Update method once per frame, as #craftworkgames suggested:
State.TouchCollection = TouchPanel.GetState();
Also I added this prop to my game state:
public bool TouchActive { get; set; }
And this is the method to check for rectangle tap. It returns true only for the first contact in tap:
private bool CheckRectangleTap(Rectangle target)
{
if (State.TouchCollection.Count == 0)
{ // if no input
return State.TouchActive = false;
}
var targetTouched = false;
foreach (var touch in State.TouchCollection)
{
if (target.Contains(touch.Position))
{
targetTouched = true;
}
}
if (targetTouched && !State.TouchActive)
{ // if target is touched and it's first contact
return State.TouchActive = true;
}
return false;
}
It doesn't seem ideal but it works for my case.

RecyclerView not clearing (notifyDataSetChanged not working)

I've had a look everywhere on here and nothing is related to my problem. Basically I've implemented a feature which changes the reading direction of my app (1 or -1) now I can get it to initially change direction and it works really well but when I get it to change back (using the same code but changing the direction) it just doesn't update. Just seems like notifyDataSetChanged(); doesn't want to work the second time...?
My code is as as follows:
private void flip() {
if (!isFlipped) {
mData.getItems().removeAll(mData.getItems());
mAdapter.notifyDataSetChanged();
isFlipped = true;
loadData(false, -1);
closeMenu();
} else {
mData.getItems().removeAll(mData.getItems());
mAdapter.notifyDataSetChanged();
isFlipped = false;
loadData(false, 1);
closeMenu();
}
}
What am I doing wrong?
Again, thanks in advance :)
Implement a public method in your RecyclerView code, e.g:
public void clearAll(){
mData.clear();
this.notifyDataSetChanged();
}
And then call that function from your activity (or Fragment):
private void flip() {
if (!isFlipped) {
mAdapter.clearAll();
isFlipped = true;
loadData(false, -1);
closeMenu();
} else {
mAdapter.clearAll();
isFlipped = false;
loadData(false, 1);
closeMenu();
}
}

EditText.setText()/getText() appears to be too slow to be used in TextWatcher

I have a TextWatcher that adds a dollar sign in front of an EditText value (it's a price field). Everything works fine except that if you type two first digits fast enough, the second digit won't appear. Once you past the first two digits it's all fine. If you type them slowly (almost a second in between) it also works fine.
Here is the TextWatcher code I am using:
#AfterTextChange(R.id.add_itemPrice) // android annotations way
void addDollar(Editable e) {
if (priceFieldBeingModified) {
return;
}
if (!e.toString().startsWith(CURRENCY_SYMB)) {
priceFieldBeingModified = true;
String newValue = CURRENCY_SYMB + e;
priceField.setText(newValue);
if (priceField.getSelectionStart() == 0) {
// move the cursor to the end
priceField.setSelection(priceField.getText().length());
}
priceFieldBeingModified = false;
}
}
priceField EditText has fixed layout_width/layout_height (in dp). From what I can gather, setText()/getText() are just too expensive but I don't know how to avoid them in this case.
priceField.getText().insert(0, CURRENCY_SYMB) doesn't do anything for some reason.
EDIT:
Looks like the problem only happens on Android 4.3 (or an Xperia Z phone). Tried a 4.1 phone - works like a charm.
Any suggestions would be appreciated, I am out of ideas with this one!
This is working fine for me:
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(s.toString().equalsIgnoreCase(""))
{
}
else if (!s.toString().startsWith("$")) {
priceFieldBeingModified = true;
String newValue = "$" + s;
e.setText(newValue);
if (e.getSelectionStart() == 0) {
// move the cursor to the end
e.setSelection(e.getText().length());
}
priceFieldBeingModified = false;
}
It checks if string is not null and it doesn't start with "$", then it adds "$" at start and moves cursor to end.

How to play sound once when two sprite collide in andengine?

Well I'm working with ball game , Every thing is working fine , Now i want to add Sound when the two balls collide each other .
I tried the following code but the sound is being repeated.I want it will play only once when collision start & not at collision maintained.
In onCreateResources:
SoundFactory.setAssetBasePath("sfx/");
try {
mSound = SoundFactory.createSoundFromAsset(getSoundManager(), this, "coll2.m4a");
} catch (IOException e) {
e.printStackTrace();
}
And added below code in onAccelerationChanged(AccelerationData pAccelerationData)
if (face.collidesWith(face1) || face.collidesWith(face2))
{
mSound.play();
}
You could have a boolean to check if the sprites have already collided. The code would look something like this.-
if (face.collidesWith(face1) || face.collidesWith(face2)) {
if (!colliding) {
colliding = true;
mSound.play();
}
} else {
colliding = false;
}

Categories

Resources