How do I execute a callback when JBullet detects a collision? - callback

So currently I have an instance of JBullet running on its own thread and I have no idea how to get information about collisions on JBullet 20101010-1.
I have tried calling ContactAddedCallback as shown below but nothing happens.
new ContactAddedCallback() {
#Override
public boolean contactAdded(ManifoldPoint cp, CollisionObject colObj0, int partId0, int index0,
CollisionObject colObj1, int partId1, int index1) {
System.out.println("Collision");
return false;
}
};

you must add ContactAddedCallback to BulletGlobals
to do that after you create a ContactAddedCallback like this ::
ContactAddedCallback myCollisionCallback = new ContactAddedCallback() {
#Override
public boolean contactAdded(
ManifoldPoint cp,
CollisionObject colObj0,
int partId0,
int index0,
CollisionObject colObj1,
int partId1,
int index1) {
System.out.println("hi i am collision !!");// :|
return false;
}
};
and add flag to rigidbody like this ::
rb = new RigidBody(constructionInfo);
rb.setCollisionFlags(CollisionFlags.CUSTOM_MATERIAL_CALLBACK);
now add to BulletGlobals Like this ::
BulletGlobals.setContactAddedCallback( myCollisionCallback );
if you want get which RigidBody are Collided do this ::
when you create a CollisionShape you must add userPointer like this ::
BoxShape groundShape = new BoxShape(new Vector3f(1000,10,1000));
rb = new RigidBody(constructionInfo);
...
groundShape.setUserPointer(rb);
and finaly in ContactaddedCallback you can check like this ::
ContactAddedCallback myCollisionCallback = new ContactAddedCallback() {
#Override
public boolean contactAdded(
ManifoldPoint cp,
CollisionObject colObj0,
int partId0,
int index0,
CollisionObject colObj1,
int partId1,
int index1) {
if (colObj0.getUserPointer().equals(rb)) {
//for sample you can push them to up
rb.applyCentralImpulse(new Vector3f(0,1,0));
}
if (colObj1.getUserPointer().equals(rb)) {
rb.applyCentralImpulse(new Vector3f(0,1,0));
}
System.out.println("hi i am collision !!");// :|
return false;
}
};

Related

How to get other player's value in Unity when I use Mirror Network?

Hello? I'm studying the MIRROR Network Now.
enter image description here
However, I have a problem about getting other player's value. This image explain what I want to do.
enter image description here
I create 3 projects. One is server(local host) and other is Client A , the other is Client B.
Firstly, I wrote code like this :
public class PlayerManager : NetworkBehaviour
{
[SyncVar(hook = nameof(onValueChanged))]
int value = 0;
private void Update()
{
if(isServer && Input.GetKeyDown("x"))
{
Message();
}
}
public override void OnStartServer()
{
Debug.Log("Here is Game Room Scene, Player add Successfully");
}
[Command]
private void Hola()
{
value++;
Debug.Log("Received Hola from the client!");
Debug.Log("Server Value : " + value);
ReplyHola();
}
[TargetRpc]
private void ReplyHola()
{
Debug.Log("Received Hola from Client!");
}
[ClientRpc]
private void Message()
{
Debug.Log("Ping...");
}
[ClientRpc]
private void UpdateValue(int value)
{
this.value = value;
}
private void onValueChanged(int oldValue, int newValue)
{
Debug.Log("New Value Detective :");
Debug.Log("Old Value : " + oldValue);
Debug.Log("New Value : " + newValue);
Debug.Log("Sum Value : " + PlayerStat.Value);
}
}
3 Projects have all same code. I referenced code from this video(https://www.youtube.com/watch?v=8tKFF0RP9Jw).
And, I wrote code about sum client A and B's code like this:
private void SumDatas()
{
foreach(var playerObj in FindObjectsOfType(typeof(GameObject)) as GameObject[])
{
if(gameObject.name == "Player(Clone)")
{
PlayerStat.Value += GameObject.Find("Player(Clone)").transform.GetComponent<PlayerManager>().GetValue();
}
}
}
PlayerStat is a static class and Code is like this:
public static class PlayerStat
{
public static int Value { get; set; }
}
Is there anybody help me?
I solved this problem. I will not delete this question for other people who will have same problem with me.
I add this code at my server project, Client A and B project:
[SyncVar(hook = nameof(onValueChanged))]
int value = 0;
int myValue = 0;
private void Update()
{
myValue = PlayerStat.Value;
}

Cannot convert Datatypes from-to

I have a class called DisplayInventory
Dictionary<InventoryObject, GameObject> itemsDisplayed = new
Dictionary<InventoryObject, GameObject>();
itemsDisplayed.Add(inventory.Container[i], obj);
the code breaks at this line (inventory.Container[i]) because it
cannot convert (field) List InventoryObject.Container.
this is my InventoryObject class
public class InventoryObject : ScriptableObject {
public List Container = new List();
public void AddItem(ItemObjectData _item, int _amount)
{
bool hasItem = false;
for (int i = 0; i < Container.Count; i++)
{
if(Container[i].item == _item)
{
Container[i].AddAmount(_amount);
hasItem = true;
break;
}
}
if(!hasItem)
{
Container.Add(new InventorySlot(_item, _amount));
}
}
}
[System.Serializable] public class InventorySlot {
public ItemObjectData item;
public int amount;
public InventorySlot(ItemObjectData _item, int _amount)
{
item = _item;
amount = _amount;
}
public void AddAmount(int value)
{
amount += value;
} }
The part where you declare the inventory variable or specifically inventory.container is missing.
Or is this the container from the InventoryObject class?
You need the specific type InventoryObject for the Dictionary.
What you are giving into it is simply just a List object that you put inside the container.
If you are refering to the container from the InventoryObject class, it really is just a List() that you hold there.
In this case the Dictionary would only need inventory as input.
Or you could change from
public List Container = new List();
to this
public List<InventoryObject> Container = new List<InventoryObject>();
This would still make more sense if this container is outside of the InventoryObject and in an Inventory class or something.

How access HeaderView in ListView?

There is a method
addHeaderView
Several headers can be added and I can get counter of them, but I do not see how can I get the view back. There is no method getHeaderView(int index), did I miss something?
My answer could be cache the view in ListView tag but maybe you can give me something more obvious.
No exists a native implementation for it but you can use the adapter to manipulate the header as describe these links:
Section header listview
Listview with section header
public class MyBaseAdapter extends BaseAdapter {
public class PojoHeader {}
public class PojoView {}
private final int TYPE_HEADER = 0;
private final int TYPE_VIEW = 0;
private final int VIEW_TYPE_COUNT = 2;
List<Object> mList;
#Override
public int getCount() {
return this.mList.size();
}
#Override
public Object getItem( final int position ) {
return this.mList.get( position );
}
#Override
public long getItemId( final int position ) {
return position;
}
#Override
public int getItemViewType( final int position ) {
if ( this.mList.get( position ) instanceof PojoHeader ) {
return this.TYPE_HEADER;
}
else if ( this.mList.get( position ) instanceof PojoHeader ) {
return this.TYPE_VIEW;
}
return super.getItemViewType( position );
}
#Override
public View getView( final int position, final View convertView, final ViewGroup parent ) {
// Your view
return null;
}
#Override
public int getViewTypeCount() {
return this.VIEW_TYPE_COUNT;
}
#Override
public boolean isEnabled( final int position ) {
if ( this.mList.get( position ) instanceof PojoHeader ) {
return false;
}
else if ( this.mList.get( position ) instanceof PojoHeader ) {
return true;
}
return true;
}
}

I'm stuck at slick graphics

I'm trying to make a game, using slick2d, and lwjgl. I don't get why this code doesn't work
firstStage.java
package net.CharlesDickenson;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class firstStage extends BasicGameState {
public bossVar bossChecker() {
if(isBeforeMiddleBoss) return bossVar.beforeBoss;
if(isMiddleBoss) return bossVar.Middle;
if(isBeforeBoss) return bossVar.beforeBoss;
if(isBoss) return bossVar.Boss;
return null;
}
#SuppressWarnings("static-access")
public firstStage(int state) {
this.state = state;
}
#Override
public void init(GameContainer _arg0, StateBasedGame _arg1)
throws SlickException {
scoreBoard = new Image("res/scoreBoard.png");
backs = new Image("res/1stageBack.gif");
isBeforeMiddleBoss = true;
isMiddleBoss = false;
isBeforeBoss = false;
isBoss = false;
_arg0.setShowFPS(false);
}
#Override
public void render(GameContainer arg0, StateBasedGame _arg1, Graphics _g)
throws SlickException {
this._g = _g;
new Mob().getGraphics(_g);//i passed graphics
new Char().getGraphics(_g);//i passed graphics
new Bullet().getGraphics(_g);//i passed graphics
_g.drawImage(scoreBoard, 550, 5);
_g.drawImage(backs, 10, 10);
_g.drawString(fps, 580, 570);
_g.drawString("High Score-> Not avaiable", 560, 60);
_g.drawString("Score-> " + currScore, 595, 80);
}
#Override
public void update(GameContainer _arg0, StateBasedGame _arg1, int arg2)
throws SlickException {
fps = "Frame Per Second-> " + _arg0.getFPS();
bossVar b = bossChecker();
switch(b) {
case beforeMiddle :
break;
case Boss :
break;
default:
break;
}
}
#SuppressWarnings("static-access")
#Override
public int getID() {
return this.state;
}
private static int state;
private static int currScore = 0;
private static final int originX = 270;
private static final int originY = 490;
public static int X = originX;
public static int Y = originY;
private static String fps;
private Image scoreBoard;
private Image backs;
private Graphics _g;
public boolean isBeforeMiddleBoss;
public boolean isMiddleBoss;
public boolean isBeforeBoss;
public boolean isBoss;
}
Char.java
package net.CharlesDickenson;
import org.lwjgl.input.Keyboard;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
public class Char extends Bullet implements Entity {
#Override
public void getGraphics(Graphics _g) {
this._g = _g;//so i got graphics, but
if(!isInit) return;
_g.drawImage(Char, getCharX(), getCharY());//this codes doesn't works.
}
#Override
public int getCharX() {
switch(VarTracker.stage) {
case 1:
return firstStage.X;
}
return 0;
}
#Override
public int getCharY() {
switch(VarTracker.stage) {
case 1:
return firstStage.Y;
}
return 0;
}
public void setCharX(int i) {
System.out.println("asdgagsd");
switch(VarTracker.stage) {
case 1:
firstStage.X += i;
}
}
public void setCharY(int i) {
System.out.println("asdgagsd");
switch(VarTracker.stage) {
case 1:
firstStage.Y += i;
}
}
#Override
public void update() {
if(!isInit) return;
_g.drawImage(Char, getCharX(), getCharY());//this code doesn't work, too.
up = Keyboard.isKeyDown(Keyboard.KEY_UP);
down = Keyboard.isKeyDown(Keyboard.KEY_DOWN);
left = Keyboard.isKeyDown(Keyboard.KEY_LEFT);
right = Keyboard.isKeyDown(Keyboard.KEY_RIGHT);
shift = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT);
z = Keyboard.isKeyDown(Keyboard.KEY_Z);
if(up && !shift) {
setCharY(6);
}
if(down && !shift) {
setCharY(-6);
}
if(left && !shift) {
setCharX(-6);
}
if(right && !shift) {
setCharX(6);
}
if(up && shift) {
setCharY(2);
}
if(down && shift) {
setCharY(-2);
}
if(left && shift) {
setCharX(-2);
}
if(right && shift) {
setCharX(2);
}
if(z) {
new Bullet().isFiring = true;
}
if(!z) {
new Bullet().isFiring = false;
}
}
#Override
public void init() {
System.out.println("<Char> Initializing...");
isInit = false;
try {
Char = new Image("res/char.png");
} catch (SlickException e) {
e.printStackTrace();
}
isInit = true;
System.out.println("<Char> Done with init()");
}
private boolean up;
private boolean down;
private boolean left;
private boolean right;
private boolean shift;
private boolean z;
private boolean isInit;
private Image Char;
private Graphics _g;
}
I passed graphics to other class using getGraphics method, to put a image, but it doesn't work.
at render method, it worked, but I can't put a image in other class.
The reason that it doesn't work is that you are using Graphics incorrectly. When Slick2d draws something, it uses the render method. This method is passed an instance of Graphics, to which you can draw stuff. When the call ends the Graphics object is no longer useful for anything. There is thus no reason to pass it to anything that doesn't use it immediately.
What you want to do is create a render method in your Mob, Char and Bullet classes. Make instances of said classes outside of the render method, for instance in init and store them in some data structure, for instance a List. In the render method, you simple traverse the list and call render or draw on each element. A quick example:
// Give the Entity interface two methods if they don't exist already:
public interface Entity {
void render(Graphics g);
void update(int delta);
}
// In firststage.java
List<Entity> list;
// In the init() method
public void init(GameContainer container, StateBasedGame game)
throws SlickException {
...
list = new ArrayList<Entity>();
list.add(new Mob());
list.add(new Char());
list.add(new Bullet());
}
// In the render method
public void render(GameContainer container, StateBasedGame game, Graphics g)
throws SlickException {
...
for (Entity e : list) {
e.draw(g);
}
}
// In the update method
public void update(GameContainer container, StateBasedGame game, int delta)
throws SlickException {
...
for (Entity e : list) {
e.update(delta);
}
}
TL;DR version: The Graphics object exists only to be drawn to in a single render call.
Render is called many times a second, so object creation in that method is not recommended.
Object oriented programming is good at modeling objects. Games tend to model a lot of objects. Make use of it.

GWT CEll Browser Real Time Update

has someone been able to correctly to update a cell browser at runtime, i.e. when u remove a node or add a node, the change is reflected immediately in the CEll Browser, because I am using a List and when i am making a change it is not being updated on the spot
You can use ListDataProvider setList(...) method for dynamic updates. Here is an example how I update cell browser via RPC:
private void loadAllData(final ListDataProvider<Data> dataProvider) {
dBservice.getAllData(new AsyncCallback<List<Data>>() {
public void onSuccess(List<Data> result) {
dataProvider.setList(result);
}
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
});
}
to refresh a cellBrowser you have to close all the child on the root node.
anyway something like this
for (int i = 0; i < cellBrowser.getRootTreeNode().getChildCount(); i++) {
cellBrowser.getRootTreeNode().setChildOpen(i, false);
}
the AsyncDataProvider calls refreshes data
private final class Model implements TreeViewModel{
private List<ZonaProxy> zonaList = null;
private List<CategoriaProxy> categoriaList = null;
public void setCategoriaList(List<CategoriaProxy> categoriaList) {
this.categoriaList = categoriaList;
}
public void setListZona(List<ZonaProxy> zonaList) {
this.zonaList = zonaList;
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public <T> NodeInfo<?> getNodeInfo(T value) {
CategoryDataProvider dataProvider1 = new CategoryDataProvider();
return new DefaultNodeInfo(dataProvider1, new CategoriaCell());
}
/**
* Check if the specified value represents a leaf node. Leaf nodes cannot be
* opened.
*/
public boolean isLeaf(Object value) {
if (value instanceof CategoriaProxy){
if (((CategoriaProxy) value).getLivello() == 3) {
return true;
}
}
return false;
}
}
private class CategoryDataProvider extends AsyncDataProvider<CategoriaProxy>
{
#Override
protected void onRangeChanged(HasData<CategoriaProxy> display)
{
requests.categoriaRequest().findAllCategorias(0, 8).with().fire(new Receiver<List<CategoriaProxy>>() {
#Override
public void onSuccess(List<CategoriaProxy> values) {
updateRowCount(values.size(), true);
updateRowData(0, values);
}
});
}
}
it Works.
Apparently it is not enough to change the data provider and refresh it.
You need also to force the affected cell to close and reopen it, as in this example
public void updateCellBrowser(String id) {
TreeNode node = getNode(cellBrowser.getRootTreeNode(),id);
if(node != null && ! node.isDestroyed()) {
TreeNode parent = node.getParent();
int index = node.getIndex();
parent.setChildOpen(index, false,true);
parent.setChildOpen(index, true, true);
}
}
In my particular example the cell ids are pathnames hence the following
implementation of getNode().
private TreeNode getNode(TreeNode node, String id) {
for(int i=0; i < node.getChildCount(); i++)
if(node.isChildOpen(i)) {
Object value = node.getChildValue(i);
if(value instanceof String) {
String nodeId = ((String) value);
if(id.equals(nodeId))
return node.setChildOpen(i, true);
if(id.startsWith(nodeId))
getNode(node.setChildOpen(i, true),id);
}
}
return null;
}