package com.sertaogames.terremoto.component;
import java.util.ArrayList;
import java.util.List;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.sertaogames.cactus2d.Cactus2DApplication;
import com.sertaogames.cactus2d.Component;
import com.sertaogames.cactus2d.components.PhysicsComponent;
public class DragAndDropComponent extends Component {
PhysicsComponent physics = null;
public static List<Vector2> snapPositions = new ArrayList<Vector2>();
private boolean snapped = false;
private Sound sfx;
@Override
public void init() {
physics = getComponent(PhysicsComponent.class);
sfx = Cactus2DApplication.loadSound("data/sound/snap.wav");
}
@Override
public void onTouchBegin(Vector2 touchPosition) {
physics.setBodyType(BodyType.KinematicBody);
}
@Override
public void onTouchStay(Vector2 touchPosition) {
Vector2 pos = screenToWorld(touchPosition.cpy());
transform.setLocalPosition(pos.sub(spriteRenderer.getHalfSize()));
checkSnap();
}
@Override
public void onTouchEnd(Vector2 touchPosition) {
if (!snapped) {
physics.setBodyType(BodyType.DynamicBody);
}
}
private Vector2 diff = new Vector2();
private void checkSnap(){
snapped = false;
for (Vector2 pos : snapPositions) {
diff.set(transform.getLocalPosition());
diff.add(new Vector2(spriteRenderer.spriteRegion.getRegionWidth()/2
,spriteRenderer.spriteRegion.getRegionHeight()/2));
diff.sub(pos);
if (diff.len2() < 5000) {
transform.setLocalPosition(new Vector2(pos).sub(new Vector2(spriteRenderer.spriteRegion.getRegionWidth()/2
,spriteRenderer.spriteRegion.getRegionHeight()/2)));
snapped = true;
break;
}
}
}
public static List<Vector2> getSnapPositions() {
return snapPositions;
}
public static Vector2 screenToWorld(Vector2 screenPosition) {
return screenPosition.mul(Cactus2DApplication.cameraZoom);
}
}