Giter Site home page Giter Site logo

physicslayout's Introduction

PhysicsLayout

Android layout that simulates physics using JBox2D. Simply add views, enable physics, and watch them fall!

See it in action with the sample app:

Google Play

Maven Central

Gradle

dependencies {
    implementation("com.jawnnypoo:physicslayout:latest.release.here")
}

Basic Usage

If you want to see what your layout looks like when physics is applied to it, simply change your root layout to a physics layout.

<com.jawnnypoo.physicslayout.PhysicsLinearLayout
  android:id="@+id/physics_layout"
  android:layout_width="match_parent"
  android:layout_height="200dp">
            
      <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"/>

      <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"/>
              
      <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello world, I have physics!"/>
            
</com.jawnnypoo.physicslayout.PhysicsLinearLayout>

Custom XML Attributes

You can also further customize the behaviour of your PhysicsLayout

<com.jawnnypoo.physicslayout.PhysicsLinearLayout
  android:id="@+id/physics_layout"
  android:layout_width="match_parent"
  android:layout_height="200dp"
  app:physics="true"
  app:gravityX="0.0"
  app:gravityY="9.8"
  app:bounds="true"
  app:boundsSize="50dp"/>
  • physics boolean, Determines if physics will be applied to the layout (Default true)
  • gravityX float, Sets the gravity in the X direction (positive is right, negative is left) (Default 0)
  • gravityY float, Sets the gravity in the Y direction (positive is down, negative is up) (Default 9.8)
  • bounds boolean, Determines if the layout should have bounds on the edges of itself (Default true)
  • boundsSize dimenstion, Sets the width/height of the bounds on the edges (Default 20dp)

Custom Physics Configuration

Each view contained within the layout has a physics configuration that it uses to create itself in the Box2D world. This defines its shape, mass, restitutaion, and other physics related variables. A custom configuration can be applied to each view as well:

<TextView
  android:id="@+id/text"
  android:layout_width="20dp"
  android:layout_height="20dp"
  app:layout_shape="circle"
  app:layout_circleRadius="20dp"
  app:layout_bodyType="kinematic"
  app:layout_fixedRotation="true"
  app:layout_friction="0.8"
  app:layout_restitution="0.3"
  app:layout_density="0.5" />

or alternatively, the Physics definition can be made programmatically:

val circleView = findViewById<View>(R.id.circle)
val config = PhysicsConfig(
    shape = Shape.CIRCLE,
    fixtureDef = fixtureDef,
    bodyDef = bodyDef
)
Physics.setPhysicsConfig(circleView, config)

This is useful especially if you have view that would be considered circular, as the default for all views is a RECTANGLE shape. Most of the time, if you are just dealing with rectangular views, the defaults will work for you and you will not have to worry about this.

Check out the sample app to see most of these things in action.

Making a Game?

This library was designed with the intention of allowing for playful animations within normal Android apps. It is not built to be a game engine or meant to compete with the likes. If you are looking to do more intense mobile games, we recommend libraries such as libGDX or Unity

License

Copyright 2024 John Carlson

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

physicslayout's People

Contributors

jaspervandeklundert avatar jawnnypoo avatar mkonecny avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

physicslayout's Issues

Problem with joints

Hello,
I'm trying to use this physics layout, but I have found a problem when, in the main activity, I create a joint between two bodies. The joint is created correctly, but it's remove again, I think it is because in the 'onLayout' the world is recreated once and once again and only the bodies are safe for the next world. To try fix it, I modify the 'createWorld' method in the Physics class, but when I save the Joints in the array like bodies, I get an error with the memory, concretly this:
java.lang.OutOfMemoryError: Failed to allocate a 154589920 byte allocation with 33554432 free bytes and 125MB until OOM

Can help me? Thanks in advance.
Are the joints really removed? or, maybe, Am I doing something wrong?

Maybe change your README.md

You just write

compile 'com.github.Jawnnypoo:PhysicsLayout:2.1.0'

in your README.md,but I find that in jitpack.io,your newest version is 2.0.0.
:)

Help with onClickListener on PhysicsLayout child view

Hi, my name is Eduardo and i have been trying to figure out a way to set a onClickListener on a PhysicsLayout child view to change its background color. The thing is, when i do, all the physics behaviour stop working. Do you have any suggestions that could help me?

Sorry if this is a obvious question, i am just starting android developing :P

Get Body after adding View dynamically

Hi,
I'm adding Views to the PhysicsLayout with addView(). I want to create a Joint between multiple dynamically added Views. How can I access the Body Instance right after adding the View so I can create a Joint?

Help with adding view to PhysicsLinearLayout

Hi John, thank you for making this awesome library. I am trying to use it with my project. But when I tried to add child views to the PhysicsLinearLayout, the animation paused when new child view was added, like

physicsLayout = (ViewGroup) rootView.findViewById(R.id.physics_layout);
physicsLayout.addView(textView, params);

When a new TextView was added to the PhysicalLinearLayout meanwhile a previously added TextView was falling down, the latter will pause at the moment the new view was added. Any idea to solve this ?

Thanks again for this awesome library!

Locked in an angle

My objects come to be blocked against the bounds of the layout
One idea to solve the problem?
Thank you.

I can't dynamically add a child layout via addView, it crashes!

It crashes when I dynamically add a child layout via the addview method.
Here is the code to add the section:

for (int i = 0; i < dataList.size(); i++) {
    JsonMap item = dataList.getJsonMap(i);
    ImageView imageView = new ImageView(this);
    Glide.with(me)
            .load(item.getString("image_url"))
            .into(imageView);
    physicsLayout.addView(imageView);
}

Here is the crash message:

java.lang.AssertionError
	at org.jbox2d.collision.shapes.PolygonShape.computeMass(PolygonShape.java:545)
	at org.jbox2d.dynamics.Fixture.getMassData(Fixture.java:253)
	at org.jbox2d.dynamics.Body.resetMassData(Body.java:687)
	at org.jbox2d.dynamics.Body.createFixture(Body.java:203)
	at com.jawnnypoo.physicslayout.Physics.createBody(Physics.kt:470)
	at com.jawnnypoo.physicslayout.Physics.createWorld(Physics.kt:347)
	at com.jawnnypoo.physicslayout.Physics.onLayout(Physics.kt:240)
	at com.jawnnypoo.physicslayout.PhysicsLinearLayout.onLayout(PhysicsLinearLayout.kt:58)
	at android.view.View.layout(View.java:24421)
	at android.view.ViewGroup.layout(ViewGroup.java:6440)
	at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1103)
	at android.view.View.layout(View.java:24421)
	at android.view.ViewGroup.layout(ViewGroup.java:6440)
	at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
	at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
	at android.view.View.layout(View.java:24421)
	at android.view.ViewGroup.layout(ViewGroup.java:6440)
	at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
	at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
	at android.view.View.layout(View.java:24421)
	at android.view.ViewGroup.layout(ViewGroup.java:6440)
	at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1891)
	at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1729)
	at android.widget.LinearLayout.onLayout(LinearLayout.java:1638)
	at android.view.View.layout(View.java:24421)
	at android.view.ViewGroup.layout(ViewGroup.java:6440)
	at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
	at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
	at android.view.View.layout(View.java:24421)
	at android.view.ViewGroup.layout(ViewGroup.java:6440)
	at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1891)
	at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1729)
	at android.widget.LinearLayout.onLayout(LinearLayout.java:1638)
	at android.view.View.layout(View.java:24421)
	at android.view.ViewGroup.layout(ViewGroup.java:6440)
	at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
	at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
	at com.android.internal.policy.DecorView.onLayout(DecorView.java:789)
	at android.view.View.layout(View.java:24421)
	at android.view.ViewGroup.layout(ViewGroup.java:6440)
	at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:4258)
	at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3583)
	at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:2465)
	at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:9305)
	at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1339)
	at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1348)
	at android.view.Choreographer.doCallbacks(Choreographer.java:952)
	at android.view.Choreographer.doFrame(Choreographer.java:882)
	at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1322)
	at android.os.Handler.handleCallback(Handler.java:958)
	at android.os.Handler.dispatchMessage(Handler.java:99)
	at android.os.Looper.loopOnce(Looper.java:205)
	at android.os.Looper.loop(Looper.java:294)

But when I preset the sub-layout in the layout xml file there is no problem, I would like to get help with that!

Applying force to views

Hi, i found your great Project and was amazed how quick this leads to cool looking results. After fiddling around a bit i was wondering how to apply a force to views. I want them to "fall" into the middle of the screen like there is the center of a huge mass. I'm trying to misuse the gravity property to simulate a force, but it would be nice to have an interface to the "bodys" of the box2d entitys.

Thanks for you work :)

Performance issue when I add more than 10 views

Hi,

I have encounter a performance issue when I built my own app.
That is when I add more than 10 object inside the view. It start getting lag and sometimes crashed.
I also download your sample app and everything seems fine.
So I make my code almost as same as yours. But the problem is still there.
Could you give my some advice or how you make your app's performance better?

Circular bounding layout

Maybe I'm missing it, but there does not appear to be a way to create a PhysicsFrameLayout (or other layout) that's boundary is a circle. I'm looking to put circle views inside a circular bounding layout. Is there a way to do this?

set "layout_fixedRotation" dynamically

Hi, Thanks for your great lib.

Is there anyway to set layout_fixedRotation dynamically?
I want to add an inflated view to PhysicsRelativeLayout in runtime, but i cannot set this feature for the inflated view.
how can I do that?

Thanks in advance.

How to update radius of already added view

I'm working on scaling the objects within physics layout.When scale objects their radius does not change and the view goes beyond boundaries. Is there any way to change the radius of already added view in the layout?

How to use fling=true in a scrollview?

I've experimented with a number of different ways to intercept the touch events, but I cannot seem to figure out how to enable fling when the PhysicsFrameLayout is in a NestedScrollView, and be able to drag the views inside it vertically.

I can drag them horizontally fine, but as soon as I start dragging vertically I get an ACTION_CANCEL MotionEvent, and my dragging of the view inside the PhysicsFrameLayout stops.

Consider making PixelsPerMeter a function of DP by default

Testing out this great library, and was a little puzzled when different DPI phones had boundaries at different positions.

I've been able to set this myself using setPixelsPerMeter but I think it would be a great default if 50 was replaced by 50/3 * density (since most phone densities today are 3 or 4)

Multi touch don't work

The fling work only for one view.
Is it possible to activate X to move objects?

Thank you

drag & drop object

Hello.
I have imported your lib in my app and am using its 'statik' feature for drag & drop ImageViews. It is a great library, thank you :)

My question is:
Is there a way to detect where user drops the object?

Edit:
When I use this code to detect user's touch release, the object (ball) doesn't move anymore:

ball.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_UP)
                    Toast.makeText(MainActivity.this, "Dropped.", Toast.LENGTH_SHORT).show();
                return true;
            }
        });

Fling not working

I have app:fling="true" and app:physics="true" in my PhysicsFrameLayout, but I cant't fling the ImageVew inside.

Is there something extra I need to do?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.