Rajawali get object center of gravity point - rajawali

Using Rajawali library i loaded object from obj file
LoaderOBJ objParser = new LoaderOBJ(mContext.getResources(),
mTextureManager, R.raw.fridge_obj);
loadModel(objParser, new IAsyncLoaderCallback() {
#Override
public void onModelLoadComplete(ALoader loader) {
Log.d(TAG, "Model load complete: " + loader);
final LoaderOBJ obj = (LoaderOBJ) loader;
mObjectGroup = obj.getParsedObject();
getCurrentScene().addChild(mObjectGroup);
}
#Override
public void onModelLoadFailed(ALoader loader) {
Log.e(TAG, "Model load failed: " + loader);
}
}, R.raw.fridge_obj);
now i want get object center of gravity point to set it on world zero point and rotate over that point. I try to get data from Geometry3D how ever i BoundingBox is null same as Vertices field.
How can i get object center of gravity without change object file?

Rajawali currently includes no method for calculating the centroid of an object. If you create a well formatted and worded issue on the github page, we can mark it as a feature request and work on adding it as it would be a useful addition.

You can load your .obj into blender and change the pivot with CTRL + ALT + SHIFT + C. Rajawali will then use the new pivot.

Related

how to destroy an object in unity

how to destroy an object in unity?
I know you have to type the command
Destroy();
but what I'm saying is that I don't know what to put between brackets.
I have tried many different ways:
public GameObject motor;
Destroy(motor);
but it does not work
using System.Collections;
using UnityEngine;
public class LogRotation : MonoBehaviour
{
[System.Serializable] //this will allow us to edit it in the editor
//a custom class representing a single rotation "element" of the log's rotation pattern
private class RotationElement
{
//to get rid of an obnoxious warning about these fields not being initialized
#pragma warning disable 0649
public float Speed;
public float Duration;
#pragma warning restore 0649
}
[SerializeField] //attribute making private fields editable in the Unity Editor
//the aforemention full rotation pattern of the log
private RotationElement[] rotationPattern;
//this will be set to the Wheel Joint 2D from the LogMotor object
private WheelJoint2D wheelJoint;
//something has to actually apply a force to the log through the Wheel Joint 2D
private JointMotor2D motor;
private void Awake()
{
//setting fields
wheelJoint = GetComponent<WheelJoint2D>();
motor = new JointMotor2D();
//starting an infinitely looping coroutine defined below right when this script loads (awakes)
StartCoroutine("PlayRotationPattern");
}
private IEnumerator PlayRotationPattern()
{
int rotationIndex = 0;
//infinite coroutine loop
while (true)
{
//working with physics, executing as if this was running in a FixedUpdate method
yield return new WaitForFixedUpdate();
motor.motorSpeed = rotationPattern[rotationIndex].Speed;
//hard coded 10000, feel free to experiment with other torques if you wish
motor.maxMotorTorque = 10000;
//set the updated motor to be the motor "sitting" on the Wheel Joint 2D
wheelJoint.motor = motor;
//let the motor do its thing for the specified duration
yield return new WaitForSecondsRealtime(rotationPattern[rotationIndex].Duration);
rotationIndex++;
//infinite loop through the rotationPattern
rotationIndex = rotationIndex < rotationPattern.Length ? rotationIndex : 0;
}
}
}
TLDR; Destroy(motor.gameObject), but it will not work if JointMotor2D doesn't inherit MonoBehaviour.
Destroy(obj) can be used to destroy a component too.You need reference it to the game-object to destroy it.
Destroy(GetComponent<RigidBody>()) would remove the RigidBody out of the game-object, rather than removing the object itself.
Destroy(motor.gameObject) should do the trick.
But upon seeing your code, it may not.As it seems like JointMotor2D isn't a MonoBehaviour, aka it doesn't exists in the game-world, hence you can't destroy it.
Depending on what your trying to destroy, you have to find a reference to it.
Simplest way is to reference it in the inspector. Or destroy itself if that is already the object you want to destroy:
// Drag-drop the object in the inspector
[SerializeField]
private GameObject toDestroyLater;
private void DestroyObject() {
Destroy(toDestroyLater);
// Destroys self
// (Aka, whatever game-object this script is attached to)
Destroy(this.gameObject);
}

item dropping system - how can i use a prefab correctly here?

my code is pretty simple, but im quite new to unity... im trying to make it so i can drop my items on the ground when i drag the out of my inventory, but cant quite manage to do so, with a few consistent errors. I have a prefab (just learned of those today), which im trying to change its sprite renderer and spawn it. Heres my code:
public class ItemWorld : MonoBehaviour
{
private Transform prefab;
private Item item;
private SpriteRenderer spriteRenderer;
void Start()
{
prefab = Resources.Load("Prefabs/pfItemWorld") as GameObject;
//myPrefab = Resources.Load("Prefabs/pfItemWorld");
}
public static ItemWorld spawnItemWorld(Vector3 position, Item item)
{
Transform transform = Instantiate(prefab, position, Quaternion.identity);
ItemWorld itemWorld = transform.GetComponent<ItemWorld>();
itemWorld.SetItem(item);
return itemWorld;
}
private void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
}
public void SetItem(Item item)
{
this.item = item;
Rect spriteRect = new Rect(0, 0, item.itemIcon.width, item.itemIcon.height);
Sprite mySprite = Sprite.Create(item.itemIcon, spriteRect, new Vector2(0.5f, 0.5f));
spriteRenderer.sprite = mySprite;
}
}
My problem is i cant manage to load my prefab and use it in Instantiate without many errors...
What is wrong with my code?
Here are the errors:
(1) Assets\Scripts\ItemWorld.cs(12,18): error CS0029: Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Transform' (yes, i know what this means, but how can i use a prefab without transform)
(2)Assets\Scripts\ItemWorld.cs(17,43): error CS0120: An object reference is required for the non-static field, method, or property 'ItemWorld.prefab'
I have tried to research but this is my last hope xd
Ill be happy for ANY help,
thanks ahead,
Gambizon
Prefabs are GameObjects and need to be instantiated and declared as such. private transform prefab should be private GameObject prefab.
After you've instantiated the object with
GameObject prefabObject = Instantiate(prefab, position, Quaternion.identity);
You can then use Transform transform = prefabObject.transform; to get the transform component of your newly instantiated prefab.
Also, if you make the prefab reference in the script public, and have this script attached to a GameObject, you can drag the prefab into the inspector so that you don't need Resources.Load("Prefabs/pfItemWorld") as GameObject, as the reference will already be there before run time.

Android Viewpager to load images from SD Card

Guys Im using the following custom code to load 20 images from resources and present in a viewpager
public class CustomPagerAdapter extends PagerAdapter {
int[] mResources = {
R.drawable.slide1,
R.drawable.slide2,
R.drawable.slide3,
R.drawable.slide4,
R.drawable.slide5,
R.drawable.slide6,
R.drawable.slide7,
R.drawable.slide8,
R.drawable.slide9,
R.drawable.slide10,
R.drawable.slide11,
R.drawable.slide12,
R.drawable.slide13,
R.drawable.slide14,
R.drawable.slide15,
R.drawable.slide16,
R.drawable.slide17,
R.drawable.slide18,
R.drawable.slide19,
R.drawable.slide20,
};
Context mContext;
LayoutInflater mLayoutInflater;
public CustomPagerAdapter(Context context) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mResources.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = mLayoutInflater.inflate(R.layout.pager_item, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(mResources[position]);
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
This works fine but I want to put the jpgs in a directory on the device so that they can be changed without recompiling the app
I think I need to get the images into the mResource array. I can get the path but not sure what format the code should be instead of using the draw-able lines
i have read articles on here but none make sense to me I am really new to this and the code looks nothing like the code I am using
can anyone point me in the right direction?
Any help is greatly appreciated
Mark
Yes, you can certainly do so. I will try to explain you the process step-by-step,
Step 1
Have a File object pointing to the path, like,
File directory = new File("path-to-directory");
Ensure that the path is to the directory with the images,
Step 2
List all the files inside the directory using listFiles() method, like
File[] allImages = directory.listFiles();
Now you have an array of all the files just like int[] mResources. The only difference being, now you have actual file references, while previously you had resource ids.
Step 3
You can just display the images in the ViewPager just like you did previously. But this is a bit tricky and can take you a considerable amount of time and code to get an image properly displayed from File.
You also need to take care of caching, so that when you load a previously loaded image again, it gets it from the cache.
To do all this, I recommend you to use this library (recommended by Google), Glide.
Setting an image is one line of code,
Glide.with(context).from(file).into(imageView);
That's it. Now you have your images displayed in a ViewPager from a directory in the device.

Get co-ordinates of image in pdf

In my project, I want to find co-ordinates of image in pdf. I tried searching itext and pdfbox, but I was not succesful. Using these co-ordinates and extracted image, I want to verify whether the extracted image is same as image present in database, and co-ordinates of image are same as present in database.
When you say that you've tried with iText, I assume that you've used the ExtractImages example as the starting point for your code. This example uses the helper class MyImageRenderListener, which implements the RenderListener interface.
In that helper class the renderImage() method is implemented like this:
public void renderImage(ImageRenderInfo renderInfo) {
try {
String filename;
FileOutputStream os;
PdfImageObject image = renderInfo.getImage();
if (image == null) return;
filename = String.format(path, renderInfo.getRef().getNumber(), image.getFileType());
os = new FileOutputStream(filename);
os.write(image.getImageAsBytes());
os.flush();
os.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
It uses the ImageRenderInfo object to obtain a PdfImageObject instance and it creates an image file using that object.
If you inspect the ImageRenderInfo class, you'll discover that you can also ask for other info about the image. What you need, is the getImageCTM() method. This method returns a Matrix object. This matrix can be interpreted using ordinary high-school algebra. The values I31 and I32 give you the X and Y position. In most cases I11 and I22 will give you the width and the height (unless the image is rotated).
If the image is rotated, you'll have to consult your high-school schoolbooks, more specifically the ones discussing analytic geometry.

How to get location of mouse in JavaFX?

I am a beginner in java(fx).
How do you get the mouse location in x and y in JavaFX? I tried using AWT's MouseInfo(also imported it), but it's not working. I also saw the code for it in Ensembles(that dragging the ball-window in "advanced stage", that's what I need to do, drag my undecorated JavaFX stage), but it also doesn't work. I am using FXML with controller, and I guess that's the main problem. Should I switch back to the single-file simple JavaFX? I know FXML is better for laying out the UI, but I can't get many of such codes to work. Or do I need some other sort of code for my controller? Please give proper codes with comments wherever possible.
If you need a bit of my code to inspect, feel free to ask.
There are a few items in your question - I'll tackle them one at a time.
How do you get the mouse location in x and y in JavaFX?
Add a mouse event handler to the appropriate JavaFX component that you want to track the mouse location in. A JavaFX mouse event will report multiple different kinds of co-ordinates. The x and y co-ordinates are relative to the top left corner of the node whose location is being monitored. The sceneX and sceneY co-ordinates are relative to the scene's top left 0,0 co-ordinates. The screenX and screenY co-ordinates are relative to the top left 0,0 co-ordinates of the current screen.
These co-ordinates are documented in the MouseEvent documentation. There is extra information in understanding co-ordinate systems in the Node and Scene documentation.
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.*;
public class MouseLocationReporter extends Application {
private static final String OUTSIDE_TEXT = "Outside Label";
public static void main(String[] args) { launch(args); }
#Override public void start(final Stage stage) {
final Label reporter = new Label(OUTSIDE_TEXT);
Label monitored = createMonitoredLabel(reporter);
VBox layout = new VBox(10);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 10px;");
layout.getChildren().setAll(
monitored,
reporter
);
layout.setPrefWidth(500);
stage.setScene(
new Scene(layout)
);
stage.show();
}
private Label createMonitoredLabel(final Label reporter) {
final Label monitored = new Label("Mouse Location Monitor");
monitored.setStyle("-fx-background-color: forestgreen; -fx-text-fill: white; -fx-font-size: 20px;");
monitored.setOnMouseMoved(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent event) {
String msg =
"(x: " + event.getX() + ", y: " + event.getY() + ") -- " +
"(sceneX: " + event.getSceneX() + ", sceneY: " + event.getSceneY() + ") -- " +
"(screenX: " + event.getScreenX()+ ", screenY: " + event.getScreenY() + ")";
reporter.setText(msg);
}
});
monitored.setOnMouseExited(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent event) {
reporter.setText(OUTSIDE_TEXT);
}
});
return monitored;
}
}
I tried using AWT's MouseInfo(also imported it), but it's not working.
Don't do this. Mixing different graphical toolkits (for example Swing/AWT and JavaFX) is an advanced topic. In general, if you are writing a JavaFX application, avoid importing anything from the java.awt namespace and the javax.swing namespace. You only really need to use those if you have a large, existing Swing based application or framework that you need to inter-operate with your JavaFX application. In this case, you don't have that situation.
I also saw the code for it in Ensembles(that dragging the ball-window in "advanced stage", that's what I need to do, drag my undecorated JavaFX stage), but it also doesn't work.
I tried the Ensemble Advanced Stage sample and dragging that stage around worked for me.
Another sample for dragging an undecorated stage in JavaFX is in the answer to How to draw a clock with JavaFX 2? which has associated sample code. The method used to make the undecorated stage draggable for the clock sample is:
/** makes a stage draggable using a given node */
public static void makeDraggable(final Stage stage, final Node byNode) {
final Delta dragDelta = new Delta();
byNode.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
// record a delta distance for the drag and drop operation.
dragDelta.x = stage.getX() - mouseEvent.getScreenX();
dragDelta.y = stage.getY() - mouseEvent.getScreenY();
byNode.setCursor(Cursor.MOVE);
}
});
byNode.setOnMouseReleased(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
byNode.setCursor(Cursor.HAND);
}
});
byNode.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
stage.setX(mouseEvent.getScreenX() + dragDelta.x);
stage.setY(mouseEvent.getScreenY() + dragDelta.y);
}
});
byNode.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
if (!mouseEvent.isPrimaryButtonDown()) {
byNode.setCursor(Cursor.HAND);
}
}
});
byNode.setOnMouseExited(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
if (!mouseEvent.isPrimaryButtonDown()) {
byNode.setCursor(Cursor.DEFAULT);
}
}
});
}
I am using FXML with controller, and I guess that's the main problem. Should I switch back to the single-file simple JavaFX? I know FXML is better for laying out the UI, but I can't get many of such codes to work.
Lack of understanding and familiarity with the underlying JavaFX APIs is probably your main problem rather than use of FXML. However the additional complexity fxml implies together with the lighter documentation and samples for it on the web may be contributing to your hardships. If use of FXML is making it difficult for you to understand how to get some JavaFX functions to work, I advise to stop using FXML for now. Code the logic by hand using the Java APIs and refer to the Oracle JavaFX tutorials and the Ensemble sample code when you encounter things which are difficult for you.
Once you are comfortable coding directly to the JavaFX API, switch back to using FXML for larger projects which contain many GUI elements. The FXML elements and attributes themselves are built almost completely upon reflection of the standard JavaFX APIs. So, if you understand the core JavaFX APIs, you also understand almost everything about FXML.
Please do not post follow up comments to this answer (as this answer is long enough as it is). If you have new questions, create a new question (one question per question).
What about using Robot for that purpose ?
http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/Robot.html
Using Robots, it is different from posting event to AWT event queue. Events are generated in the native event queue. Actually, with Robot.mouseMove you will not only set mouse position and not only get position.
For getting mouse position, you may stick to MouseInfo
import java.awt.MouseInfo;
// get the mouse's position
Point p = MouseInfo.getPointerInfo().getLocation();
It's not working: are you with Mac ? Which is your version of JavaFX ? seems to be issues corrected for FX8. For mac only, you may use
com.sun.glass.ui.Robot robot =
com.sun.glass.ui.Application.GetApplication().createRobot();
// getPosition of the mouse in Mac
int x = robot.getMouseX();
int y = robot.getMouseY();
JavaFx 8 WindowEvent doesn't provide the (x,y) location of the mouse, unfortunately. I solved this (and it works fine) by using the AWT MouseInfo like this:
Tooltip t = new Tooltip();
Tooltip.install(yournode, t);
t.setOnShowing(ev -> {// called just prior to being shown
Point mouse = java.awt.MouseInfo.getPointerInfo().getLocation();
Point2D local = yournode.screenToLocal(mouse.x, mouse.y);
// my app-specific code to get the chart's yaxis value
// then set the text as I want
double pitch = yaxis.getValueForDisplay(local.getY()).doubleValue();
double freq = AudioUtil.pitch2frequency(pitch);
t.setText(String.format("Pitch %.1f: %.1f Hz %.1f samples", pitch, freq, audio.rate / freq));
});

Resources