Unable to jump in Andengine with Box2D - andengine

I want to make player jumps following this tutorial but I can't. Please take a look into my code and help me to fix it. Here is my codes:
mPhysicsWorld = new PhysicsWorld(new Vector2(0,
SensorManager.GRAVITY_EARTH),false);
sapo = new Sapo(100,100,mVertexBufferObjectManager,mCamera,mPhysicsWorld) {
#Override
public void onDie() {}
};
attachChild(sapo);
sapo.jump();
public abstract class Sapo extends AnimatedSprite {
private Body mBody;
public Sapo(float pX, float pY, VertexBufferObjectManager vbo, Camera camera, PhysicsWorld physicsWorld)
{
super(pX, pY, ResourceManager.getInstance().mSapoTiledTextureRegion,vbo);
createPhysics(camera, physicsWorld);
}
private void createPhysics(final Camera camera, PhysicsWorld physicsWorld)
{
mBody = PhysicsFactory.createBoxBody(physicsWorld, this, BodyType.DynamicBody, PhysicsFactory.createFixtureDef(1f,1f,1f));
}
public abstract void onDie();
public void jump() {
mBody.setLinearVelocity(new Vector2(mBody.getLinearVelocity().x,-100));
}
}

I found the problem. I forgot to register the physic handler, like this:
myScence.registerUpdateHandler(mPhysicsWorld);

Related

How to Randomly disable box collider in unity

i have two simple 3d cube objects a,b. so my task is to randomly disable box collider one of the object every time game start.
my initial thought is randomly generate Boolean and if it is false then disable the box collider.
You can add you cube's to array and use Random.Range(0, yourArray.Length) to get index of the cube which should be deactivated. In your case it will be some overhead but this solution will be work for different cube`s count in the future.
In code it will looks like:
// You can serialize this array and add cubes from Inspector in Editor
// or add script with this code to the parent gameobject
// and use GetComponentsInChildren<BoxCollider>() to get all colliders
var cubes = new BoxCollider[2] {firstCube, secondCube};
var cubeToDeactivationIndex = Random.Range(0, cubes.Length);
cubes[cubeToDeactivationIndex].enabled = false;
About your second question. If I understand correctly, implementation will be next:
using System;
using UnityEngine;
using UnityEngine.Assertions;
using Random = UnityEngine.Random;
// Interface need to provide limited API
// without open references to gameobject and transform of the object
public interface ICollidable
{
event Action<ICollidable> OnCollided;
int HierarchyIndex { get; }
void DisableCollider();
}
// This component you should add to the object which will collide with player
public class CollidableObject : MonoBehaviour, ICollidable
{
[SerializeField]
private Collider _objectCollider;
public event Action<ICollidable> OnCollided;
public int HierarchyIndex => transform.GetSiblingIndex();
private void Start()
{
Assert.IsNotNull(_objectCollider);
}
//Here you can use your own logic how to detect collision
//I written it as example
private void OnCollisionEnter(Collision collision)
{
if (collision.transform.CompareTag("Player")) {
OnCollided?.Invoke(this);
}
}
public void DisableCollider()
{
_objectCollider.enabled = false;
}
}
// This component should be on the parent gameobject for your `
// collidable objects. As alternative you can serialize array
// and add all collidable objects from the Inspector but in that
// case signature of the array should be CollidableObject[]
// because Unity can`t serialize interfaces
public class RamdomizedActivitySwitcher : MonoBehaviour
{
private ICollidable[] _collidableObjects;
private void Awake()
{
_collidableObjects = GetComponentsInChildren<ICollidable>(true);
foreach (var collidable in _collidableObjects)
{
collidable.OnCollided += DisableObjectWhenMatch;
}
}
private void DisableObjectWhenMatch(ICollidable collidedObject)
{
var randomIndex = Random.Range(0, _collidableObjects.Length);
if (randomIndex == collidedObject.HierarchyIndex) {
collidedObject.DisableCollider();
}
}
}
}

(Unity3d) **nullreferenceexception** thrown when *instance.lockpos()* is called; plus how to make an object maintain its starting rotation

I've run up against a little problem, and I can't seem to find the solution.
I'm putting together a game in Unity3d that includes these gauntlets that can control the environment, i.e. raise downed bridges, open doors, etc. First, I'm just trying to allow the gauntlets to access objects from afar, and I found a telekinesis tutorial online that I am trying to pseudo-repurpose.
This script is supposed to raise a bridge (hence BridgeMover) until it hits a specific position and then lock it in place. Unfortunately, I'm throwing a null reference exception when the bridge hits the "lockbox" object, which is a small cube on the edge of the bridge ramp leading up to the bridge. I know this is simple, but I can't quite conceptualize it, and I've just been staring at it for a few days. This is my big issue, and any help would be appreciated.
In other news, I'm also trying to have the bridge rise as a flat plane instead of following the rotation of the cast ray, and would appreciate any advice about that as well, but I would understand if y'all want me to suffer through on that one. I'm pretty sure it has something to do with the Lerp, which I still don't really understand.
In the hierarchy, I have a handhold object, which is a child of the gauntlet object, which is a child of the camera, which is a child of the player. So
Player
Camera
Gauntlet
handHold
The lockbox object is a child of the ramp that it's attached to. So:
Ramp
Lockbox
Also, this isn't a criticism of the tutorial; I'm just swimming slightly out of my depths here. The tutorial, for those interested, can be found here.
public class HandController : MonoBehaviour
{
public static BridgeMover instance;
public Camera mainCamera;
Rigidbody rbOfHeldObject;
GameObject heldObject;
public GameObject handHold;
bool holdsObject = false;
float interactionDistance = 100;
float slideSpeed = 2;
Quaternion currentRotation;
private void Start()
{
mainCamera.GetComponent<Camera>();
}
private void Update()
{
//HandMove();
if (Input.GetMouseButtonDown(0) && !holdsObject)
Raycast();
if (Input.GetMouseButtonUp(0) && holdsObject)
ReleaseObject();
if (holdsObject && instance.LockPos())
LockObject();
if(holdsObject)
{
if (CheckDistance() >= 0.1f)
MoveObjectToPosition();
}
}
private void Raycast()
{
Ray ray = mainCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, interactionDistance))
{
if(hit.collider.CompareTag("Bridge"))
{
heldObject = hit.collider.gameObject;
heldObject.transform.SetParent(handHold.transform);
holdsObject = true;
rbOfHeldObject = heldObject.GetComponent<Rigidbody>();
rbOfHeldObject.constraints = RigidbodyConstraints.FreezeAll;
}
}
}
public float CheckDistance()
{
return Vector3.Distance(heldObject.transform.position, handHold.transform.position);
}
private void MoveObjectToPosition()
{
currentRotation = heldObject.transform.rotation;
heldObject.transform.position = Vector3.Lerp(heldObject.transform.position,
handHold.transform.position, slideSpeed * Time.deltaTime);
heldObject.transform.rotation = currentRotation;
}
private void ReleaseObject()
{
rbOfHeldObject.constraints = RigidbodyConstraints.None;
heldObject.transform.parent = null;
heldObject = null;
holdsObject = false;
}
private void LockObject()
{
rbOfHeldObject.useGravity = false;
heldObject.transform.parent = null;
heldObject = null;
holdsObject = false;
}
}
And then in the BridgeMover class:
public class BridgeMover : MonoBehaviour
{
public static BridgeMover instance;
bool lockPos = false;
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "LockBox")
{
lockPos = true;
}
}
public bool LockPos()
{
return lockPos;
}
}
Any help would be appreciated. Also, if any further information is needed, let me know and I'll add it.
It looks like you're trying to implement a singleton instance for BridgeMover. Unfortunately, you don't have your instance defined. Here's the standard Unity method for creating a singleton implemented in your BridgeMover code:
public class BridgeMover : MonoBehaviour
{
public static BridgeMover instance;
bool lockPos = false;
void Awake()
{
if(instance == null)
{
instance = this;
}
else
{
Destroy(this.gameObject);
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "LockBox")
{
lockPos = true;
}
}
public bool LockPos()
{
return lockPos;
}
}
Additionally, in your HandController class you should not declare a static BridgeMover. Instead, reference the static instance properly:
public static BridgeMover instance;
if (holdsObject && BridgeMover.instance.LockPos())

Unity Game Object Controlled by real light spot on the wall

We have got various controllers developed for moving gameobjects. I have used magnetometer/gyro sensor to move game object using MUVSlide through following code:
using UnityEngine;
using ForestIndieGames.Muvslide;
public class Connection : MonoBehaviour {
private static bool created = false;
private bool newInputAvailable;
private MuvslideConnection muvslideConn;
private void Awake()
{
if (!created)
{
DontDestroyOnLoad(this.gameObject);
created = true;
muvslideConn = new MuvslideConnection();
}
}
private void OnApplicationQuit()
{
if (muvslideConn != null)
muvslideConn.Close();
}
private void Update()
{
if (muvslideConn.GetInputManager().IsNewMotionAvailable())
newInputAvailable = true;
}
public bool IsNewInputAvailable()
{
bool result = newInputAvailable;
newInputAvailable = false;
return result;
}
public Vector3 GetAngles()
{
float[] angles = muvslideConn.GetInputManager().GetOrientationDegrees();
return new Vector3(angles[0], angles[1], angles[2]);
}
}
What I am trying to achieve is to move a gameobject by a real light spot on the wall. The spot is on the wall and fed through a camera. When the spot moves I want game object to follow exactly. The light spot can be a specific color or IR or UV etc.
Any leads please

Script code only seems to work on single instance of prefb

I am experiencing the strangest issue
I have a ray cast and when it touches a certain layer it calls my function which does a small animation.
The problem is, this only works on a single object, I have tried duplicating, copying the prefab, dragging prefab to the scene, it doesn't work.
Now I have this code below, and as you can see I have this line which allows me to access the script on public PlatformFall platfall; so I can call platfall.startFall();
Something I've noticed, If I drag a single item from the hierarchy to the public PlatFall in Inspector then that SINGLE object works as it should. ( in that it animates when startFall is called). HOWEVER, if I drag the prefab from my project to the inspector then they do not work. (Even if debug log shows that the method is called animation does not occur).
public class CharacterController2D : MonoBehaviour {
//JummpRay Cast
public PlatformFall platfall;
// LayerMask to determine what is considered ground for the player
public LayerMask whatIsGround;
public LayerMask WhatIsFallingPlatform;
// Transform just below feet for checking if player is grounded
public Transform groundCheck;
/*....
...*/
Update(){
// Ray Casting to Fallingplatform
isFallingPlatform = Physics2D.Linecast(_transform.position, groundCheck.position, WhatIsFallingPlatform);
if (isFallingPlatform)
{
Debug.Log("Here");
platfall.startFall();
}
Debug.Log(isFallingPlatform);
}
}
Platform Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformFall : MonoBehaviour
{
public float fallDelay = 0.5f;
Animator anim;
Rigidbody2D rb2d;
void Awake()
{
Debug.Log("Awake Called");
anim = GetComponent<Animator>();
rb2d = GetComponent<Rigidbody2D>();
}
private void Start()
{
Debug.Log("Start Called");
}
//void OnCollisionEnter2D(Collision2D other)
//{
// Debug.Log(other.gameObject.tag);
// GameObject childObject = other.collider.gameObject;
// Debug.Log(childObject);
// if (other.gameObject.CompareTag("Feet"))
// {
// anim.SetTrigger("PlatformShake");
// Invoke("Fall", fallDelay);
// destroy the Log
// DestroyObject(this.gameObject, 4);
// }
//}
public void startFall()
{
anim.SetTrigger("PlatformShake");
Invoke("Fall", fallDelay);
Debug.Log("Fall Invoked");
// destroy the Log
// DestroyObject(this.gameObject, 4);
}
void Fall()
{
rb2d.isKinematic = false;
rb2d.mass = 15;
}
}
I understood from your post that you are always calling PlatformFall instance assigned from inspector. I think this changes will solve your problem.
public class CharacterController2D : MonoBehaviour {
private PlatformFall platfall;
private RaycastHit2D isFallingPlatform;
void FixedUpdate(){
isFallingPlatform = Physics2D.Linecast(_transform.position, groundCheck.position, WhatIsFallingPlatform);
if (isFallingPlatform)
{
Debug.Log("Here");
platfall = isFallingPlatform.transform.GetComponent<PlatformFall>();
platfall.startFall();
}
}
}
By the way, i assume that you put prefab to proper position to cast. And one more thing, you should make physics operations ,which affect your rigidbody, in FixedUpdate.

How to get touched location in AndEngine?

I'm new in AndEngine and there is too many hard things for me now..
I want to know where I touched when I touch anywhere, and give actions by those locations with x and y. Can anybody help me?
Go throught the AndEngine Examples. There are two methods. Either you register touch on an Entity, as shown for example in TouchAndDrag example:
final Sprite sprite = new Sprite(centerX, centerY, this.mFaceTextureRegion, this.getVertexBufferObjectManager()) {
#Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
return true;
}
};
Or you use the touch listener on a Scene. You have to implement the IOnSceneTouchListener and then set it in your scene:
public class MyListener implements IOnSceneTouchListener {
#Override
public boolean onSceneTouchEvent(Scene pScene, final TouchEvent pSceneTouchEvent) {
if (pSceneTouchEvent.isActionDown()) {
//execute action.
}
return false;
}
}
}
...
scene.setOnSceneTouchListener(new MyListener ());
You can find most of the code needed in the examples already. See this tutorial on how to add them to Eclipse.