JavaScript code not working properly on Android - android

I'm writing a game of checkers with QML, and I have this component which encompasses the player piece and it's mouse area.
When the mouse is pressed, and the user moves the mouse, the cell underneath is highlighted yellow. This and snapping works on Ubuntu, but when I test it on Android, only dragging pieces seems to work.
This is it working on Ubuntu
Here's the code for the player piece:
Component {
id: playerPiece
Image {
id: image
property int cx: 0
property int cy: 0
x: board.x + (cx * window.cellSize)
y: board.y + (cy * window.cellSize)
property int pieceIndex: -1
property int pieceType: 0
MouseArea {
id: ma
anchors.fill: parent
enabled: GameState.playerTurnId == 1 && (pieceType & 1) == 1
drag.target: parent
drag.axis: Drag.XAxis | Drag.YAxis
property int targetCellX: -1
property int targetCellY: -1
onReleased: {
// console.log("released")
if (GameState.lastHighlightedIndex != -1
&& GameState.lastHighlightedY != -1) {
board.children[GameState.lastHighlightedY].children[GameState.lastHighlightedX].children[0].visible = false
if (targetCellX != -1 && targetCellY != -1) {
console.log(targetCellX)
var piece = GameState.playerPieceQMLItems[image.pieceIndex]
console.log(`cx ${targetCellX} cy ${targetCellY}`)
piece.cx = targetCellX
piece.cy = targetCellY
//hack to recalculate positions
board.x++
board.x--
board.y++
board.y--
targetCellX = -1
targetCellY = -1
}
}
}
onPositionChanged: {
if (drag.active) {
// console.log("dragging")
var mousePos = NativeFunctions.globalMousePos()
targetCellX = Math.floor(
(mousePos.x - window.x - board.x) / window.cellSize)
targetCellY = Math.floor(
(mousePos.y - window.y - board.y) / window.cellSize)
if ((targetCellX > -1 && targetCellX < 8) && (targetCellY > -1
&& targetCellY < 8)) {
GameState.tileState[targetCellX + (targetCellY * 8)] = 3
//update the board row column child item
var item = board.children[targetCellY].children[targetCellX]
if (item instanceof Rectangle) {
//remove the highlight from the last highlighted cell
if (GameState.lastHighlightedIndex != -1
&& GameState.lastHighlightedY != -1) {
board.children[GameState.lastHighlightedY].children[GameState.lastHighlightedX].children[0].visible = false
}
item.children[0].visible = true
//console.log(`selected ${GameState.playerPieceQMLItems[image.pieceIndex]}, pieceIndex ${image.pieceIndex}`)
//console.log(`${item.children[1].id}`)
GameState.lastHighlightedX = targetCellX
GameState.lastHighlightedY = targetCellY
}
}
}
}
}
sourceClipRect: {
if (GameState.cf(pieceType, GameState.TS_P1)) {
//king flag set
if (GameState.cf(pieceType, GameState.TS_PK)) {
return Qt.rect(0, 326, 338, 338)
} else {
return Qt.rect(0, 0, 338, 338)
}
} else if (GameState.cf(pieceType, GameState.TS_P2)) {
//king flag set
if (GameState.cf(pieceType, GameState.TS_PK)) {
return Qt.rect(0, 326, 338, 338)
} else {
return Qt.rect(534, 0, 338, 338)
}
}
}
source: "qrc:/pieces.png"
}
}
Which is a part of https://github.com/ben-cottrell-nz/checkers/blob/master/main.qml.
Why is the highlighting and snapping functionality not working when I test my application on Android?

I found out that my method exposed from C++, NativeMethods::globalMousePos was the issue: on Android it was returning -2147483648 for x and y, this was being returned from QCursor::pos.
I changed mousePos in my QML code to use the builtin function mapToGlobal:
var mousePos = mapToGlobal(mouse.x, mouse.y)
Highlighting and snapping to Rectangles works on Android now.

Related

Smooth map rotation in navigation kotlin android

I have problem with smooth map rotation. I use Sensor and onSensorChanged to get direction which side the user is looking at. Then I put it to math degrees (rage -180 : 180)
degres = Math.toDegrees(mOrientation.get(0).toDouble())
and then pass it to other function
if (gps != null) {
if(degres!! !in lastDegres!!-10..lastDegres!!+10 && degres!!>0 || degres!! !in lastDegres!!-10 ..lastDegres!!+10 && degres!!<0 ){
//here
lastDegres = degres
}
}
if statement avoid shaking map when sensor get a little movement.
My problem is what I have type in this if statement to smoothly rotate map. I already trying something like this :
if (gps != null) {
if(degres!! !in lastDegres!!-10..lastDegres!!+10 && degres!!>0 || degres!! !in lastDegres!!-10 ..lastDegres!!+10 && degres!!<0 ){
var result = (lastDegres!! - (degres!! )).toInt()
for (i in 0..result) {
setOrientation(((180 + lastDegres!! + i ).toFloat()))
update()
}
lastDegres = degres
}
}
but it's work only in only right direction, any advices how to allow to rotate smoothly to left and right ?
// ANSWER
if u want use this next step is find closest site left or right to actually position
if (gps != null) {
realpos = degres!! * -1
if (realpos < 0) realpos += 360
dif = if (realpos > lastDegres!!) { realpos - lastDegres!! } else { (lastDegres!! - realpos) }
if (dif > 10) {
if(realpos > lastDegres!!){
for (i in 1..dif.toInt()*50000) {
orientation = (lastDegres!!.toFloat()+i/50000)
update()
}
}else if (lastDegres!! > realpos) {
for (i in 1..dif.toInt()*50000){
orientation = (lastDegres!!.toFloat()-i/50000)
update()
}
}
lastDegres = realpos
}

Image to binary value - Pixel Value

I need to convert image to a hexadecimal value. When I try to get a color code of specific pixel on uiimage I got the wrong value. In Java I'm using bitmap.getpixel() method to reach pixel color and I'm getting correct value which is 255 but on swift same image pixel returning 0. Do you have any comment on this? or Is there a convenient way to convert image to a hexadecimal?
Java Code Reference
private func createPrintableObject (img:UIImage) -> String{
let sb = StringBuilder()
let height:Int = Int(img.size.height)
let width:Int = Int(img.size.width)
var index = 0
var rgb:Int,red:Int,green:Int,blue:Int
var rgbColor:UIColor
var auxBinaryChar: [Character] = ["0","0","0","0","0","0","0","0"]
widthBytes = width / 8
if(width % 8 > 0){
widthBytes = ((Int)(width/8))+1
}else{
widthBytes = width / 8
}
self.total = widthBytes * height
let pixelData = img.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
for h in 0...height-1 {
for w in 0...width-1 {
let value = Int(data[((width * w) + h) * 4])
//value returns in Java "-1" but In Swift returning "0"
// JAVA -> rgb = bitmapImage.getPixel(w, h); returning "-1"
red = (value >> 16) & 0x000000FF
green = (value >> 8) & 0x000000FF
blue = (value) & 0x000000FF
let totalColor = red + green + blue
var auxChar = "1"
if(totalColor > self.blackLimit){
auxChar = "0"
}
auxBinaryChar[index] = auxChar[0]
index+=1
if(index == 8 || w == (width-1)){
sb.append(self.fourByteBinary(binaryStr: String(auxBinaryChar)))
auxBinaryChar = ["0","0","0","0","0","0","0","0"]
index = 0
}
}
sb.append("\n")
}
return sb.toString()
}
private func fourByteBinary(binaryStr:String) -> String{
var decimal:Int = Int(binaryStr,radix: 2) ?? 0
if(decimal > 15){
return String(decimal, radix: 16, uppercase: true)
}else{
decimal = Int(String(decimal),radix:16) ?? 0
return "0" + String(decimal, radix: 16, uppercase: true)
}
}

Having problems with decrementing particular variables for particular touch events active at once, on the screen

So I am making a game where the user places four fingers of their hand on the screen which produces four circles on those touches on the screen and indicators above these with an offset. An indicator goes off on a particular circle and the user requires to touch up which increments their score and back down to the circle they lifted their finger from. I have four variables which handle the scoring for each of these fingers for reasons to use them as statistics later on, the incrementing part of the game works as it should. However, my problem is when decrementing, at times the scores for each circle decrements properly but most times it is not doing it correctly.
Below is the segment of code where my problem is currently:
public void scoreDeducter(OrthographicCamera cam, float elapsedTime,
int currentIndex) {
//the for loop iterating over the 4 circles on the screen
for (int placerIndex = 0; placerIndex < placerCoordinates.length; placerIndex++) {
Vector3 placerVector = new Vector3(
placerCoordinates[placerIndex].x,
placerCoordinates[placerIndex].y, 0);
cam.unproject(placerVector);
//the currentIndex is where the indicator has gone green and so to avoid
//the score to decrement for that pointer we don't execute the inner loop
//as we would like to increment score on touch up.
if (currentIndex != placerIndex) {
//goes through the various touch coordinates currently on the screen
for (int pointer = 0; pointer < 5; pointer++) {
Vector3 touchVector = new Vector3(Gdx.input.getX(pointer),
Gdx.input.getY(pointer), 0);
//we unproject the pointer's coordinates x and y
cam.unproject(touchVector);
//this is the distance between the placer (circle) and the touch on the screen
//for the pointer
float distance = placerVector.dst(touchVector.x,
touchVector.y, 0);
int radius = 20;
//checks whether this pointer has been touched
boolean isCurrentTouched = Gdx.input.isTouched(pointer);
//boolean isCurrentTouched = Gdx.input.isTouched();
//if the distance is less than the circle's radius and is touched
//then we know that the person hasn't made an error, therefore we skip the
//pointer to 5, without making any further checks whether it is touched or not.
if (distance < radius && isCurrentTouched) {
pointer = 5;
}
//otherwise should the pointer's value be 4 and the if statement
//condition above fails we decrement the score off a circle as they
//lifted their finger on the placer where the indicator hasn't gone green
else if (pointer == 4) {
if (elapsedTime >= 5.0f && !isCurrentTouched) {
if (placerIndex == 0 && f1Score != 0) {
f1Score = f1Score - 1;
}
if (placerIndex == 1&& f2Score != 0) {
f2Score = f2Score - 1;
}
if (placerIndex == 2 && f3Score != 0) {
f3Score = f3Score - 1;
}
if (placerIndex == 3 && f4Score != 0) {
f4Score = f4Score - 1;
}
}
}
}
}
}
}
This then gets rendered in my GameRenderer class in render method:
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
System.out.println("f1 score: " + world.getFingerPlacer().getF1Score()
+ " f2 score: " + world.getFingerPlacer().getF2Score()
+ " f3 score: " + world.getFingerPlacer().getF3Score()
+ " f4 score: " + world.getFingerPlacer().getF4Score());
// System.out.println("f1 Errors: " + f1Errors + " f2 Errors: " +
// f2Errors + " f3Errors: " + f3Errors + " f4Errors: " + f4Errors);
// System.out.println("The score: "+
// world.getFingerPlacer().getTotalScore());
if ((!world.getFingerPlacer().arePlacersFilled() && !world
.getIndicator().areIndicatorsFilled()) && Gdx.input.isTouched()) {
world.getFingerPlacer().addFingerPlacers();
world.getIndicator().generateCoords();
}
if (world.getFingerPlacer().arePlacersFilled()
&& world.getIndicator().areIndicatorsFilled()) {
// we sort the lists so that the indicators match with the
// corresponding placers
world.bubblesort(world.getFingerPlacer().getPlacerCoords());
world.bubblesort(world.getIndicator().getIndicatorCoords());
// the rendering of the placers take place
renderFingerPlacers();
renderIndicators();
renderIndicatorColour(delta);
timeKeeper(delta);
}
}
And my scoreDeducter() method gets called in the renderIndicatorColour method:
public void renderIndicatorColour(float delta) {
shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(50 / 130f, 210 / 130f, 56 / 130f, 1f);
Vector3 touchVector = new Vector3(world.getIndicator()
.getIndicatorCoords()[index].x, world.getIndicator()
.getIndicatorCoords()[index].y, 0);
camera.unproject(touchVector);
shapeRenderer.rect(touchVector.x, touchVector.y, 20, 10);
shapeRenderer.end();
elapsedTime += delta;
justTouchedUp = Gdx.input.getInputProcessor().touchUp(
(int) world.getFingerPlacer().getPlacerCoords()[index].x,
(int) world.getFingerPlacer().getPlacerCoords()[index].y, 0, 0);
if (justTouchedUp) {
wasTouchedUp = true;
}
world.getFingerPlacer().scoreDeducter(camera, elapsedTime, index);
}
Thank you in advance.

Up and Down Enemy Movement using translate corona sdk

i want my bird to have a up and down movement when it plays here is my code
function updateMons2()
for a = 1, mons2.numChildren, 1 do
physics.addBody(mons2[a],"kinematic")
if(mons2[a].isAlive == true) then
(mons2[a]):translate(speed * -1, 0)
if(mons2[a].x < -80) then
mons2[a].x = 1000
mons2[a].y = 500
mons2[a].isAlive = false
end
end
end
end
this code only does is from right to left i want my bird to move up and down while it is going left can someone help me?
Here is a sample. try this:
local mons2 = {}
local yPos = {}
for i=1,2 do
mons2[i] = display.newImageRect("1.png",50,50)
mons2[i].x = 100
mons2[i].y = 100+(100*(i-1))
mons2[i].isAlive = true
yPos[i] = mons2[i].y
end
speed = 10
count_ = 0
function updateMons2()
count_ = count_ + 1
for a = 1, 2, 1 do
physics.addBody(mons2[a],"kinematic")
if(mons2[a].isAlive == true) then
mons2[a]:translate(speed * -1, 0)
transition.to(mons2[a],{time=50,y=yPos[a]+(20*(count_%2)*-1)})
if(mons2[a].x < -80) then
mons2[a].x = 350
end
end
end
end
timer.performWithDelay(100,updateMons2,-1)
Keep Coding........... :)

Move animated movieClips using buttons instead of arrow keys

I'm trying to develop a game where I want my character to run when I click a button, and continue running if I hold the button. I'm new to ActionScript 3, so I'm a bit lost here.
I've found code that satisfies my requirements; but it uses the arrow keys, as below:
function moveRunKei() {
if (Key.isDown(Key.RIGHT)) {
dx = 15; //speed
runKei._xscale = 50;
} else if (Key.isDown(Key.LEFT)) {
dx = -15;
runKei._xscale = -50;
} else {
dx = 0;
}
runKei._x += dx;
if (runKei._x < 100) runKei._x = 100; //30
if (runKei._x > 550) runKei._x = 550;
if (dx != 0 && runKei._currentframe == 1) {
runKei.gotoAndPlay("run");
} else if (dx == 0 && runKei._currentframe != 1) {
runKei.gotoAndStop("stand");
}
}
this.onEnterFrame = function(){
moveRunKei();
}
I need to be able to do this using buttons.
////////////////////////////////////////////////////////////////////////////////////
import flash.events.Event;
var mouseDown:Boolean;
var speed:Number=4;
addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onMouseDown(event:MouseEvent):void
{
mouseDown = true;
}
function onMouseUp(event:MouseEvent):void
{
mouseDown = false;
}
function onEnterFrame(event:Event):void
{
if (mouseDown)
{
runKei.gotoAndPlay("Run");
runKei.x += speed;
}
}
This code able to make my character move continuously when I hold the button but it didn't animate while it move(the character freeze until I release the button) - I'm not sure how to explain it.
You'll need to add event listeners for mouse down and mouse up on each of the buttons for movement. Then have booleans that keep track of whether or not the button is down.
It's worth mentioning the code you've linked seems to be actionscript2 so I've changed it to work with as3
var leftDown:Boolean = false;
var rightDown:Boolean = true;
leftButton.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown)
rightButton.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown)
leftButton.addEventListener(MouseEvent.MOUSE_UP, onMouseUp)
rightButton.addEventListener(MouseEvent.MOUSE_UP, onMouseUp)
leftButton.addEventListener(MouseEvent.MOUSE_OUT, onMouseUp)
rightButton.addEventListener(MouseEvent.MOUSE_OUT, onMouseUp)
function onMouseDown(e:MouseEvent):void
{
//since you can't click on two things at once, this is fine.
rightDown = (e.target == rightButton);
leftDown = (e.target == rightButton);
}
function onMouseDown(e:MouseEvent):void
{
//since you can't click on two things at once, this is fine.
rightDown = (e.target == rightButton);
leftDown = (e.target == leftButton);
}
function moveRunKei()
{
if (rightDown) {
dx = 15; //speed
runKei.scaleX = -0.5;
} else if (leftDown) {
dx = -15;
runKei.scaleX = -0.5;
} else {
dx = 0;
}
runKei.x += dx;
if (runKei.x < 100) runKei.x = 100; //30
if (runKei.x > 550) runKei.x = 550;
if (dx != 0 && runKei.currentFrame == 1)
{
runKei.gotoAndPlay("run");
}
else if (dx == 0 && runKei.currentFrame != 1)
{
runKei.gotoAndStop("stand");
}
}
this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onEnterFrame(e:Event):void
{
moveRunKei();
}

Categories

Resources