Drawing smoother pixel trails with as3 - android

I am trying to make a slice effect when user moves his fingers on the screen on Android Device like in Fruit Ninja
I have a movieClip named Particle which has a circle
I tried following
stage.addEventListener(MouseEvent.MOUSE_DOWN , stratSlice);
stage.addEventListener(MouseEvent.MOUSE_UP , endSlice);
function startSlice(e:MouseEvent):void
{
stage.addEventListener(MouseEvent.MOUSE_MOVE , drawSlice);
}
function endSlice(e:MouseEvent):void
{
stage.addEventListener(MouseEvent.MOUSE_MOVE , drawSlice);
}
function drawSlice(e:MouseEvent):void
{
var p:Particle = new Particle();
addChild(p);
p.x = mouseX;
p.y = mouseY;
}
but when I run it The slice is broken I want it to be seamless.

Adding e.updateafterevent() in the mouse move handler might improve performance a bit.
In general your code will probably not work as well as other particle effects you see in games such as fruits ninja. For good results you will need to use a particle engine such as
StarDust: https://code.google.com/p/stardust-particle-engine/
Flint: http://flintparticles.org/
Partigen: http://www.desuade.com/partigen/engine
Starling Particle: https://github.com/PrimaryFeather/Starling-Extension-Particle-System
I know starling works great on android, not sure about the others

Related

Unity 2D Android ball jumping script AddForce

I am new to Unity and I am trying to learn the basics, I learn physics at school(ten grade).
What I have done so far - added a ball to my project and used gravity on it with RigidBody.
I want to make the ball jump suddenly on air when there is some touch input, for example - flappy bird.
My script is basic:
void Update()
{
if (Input.touchCount == 1)
{
GetComponent<Rigidbody>().AddForce(new Vector2(0, 10), ForceMode.Impulse);
}
}
With this script, the ball is falling(gravity) and when I touch the script, is Y coordinate changes but it happens by sudden (no animation) and it changes by like ~1 and continue falling(I can't keep the ball on screen) , also I can make it jump only once, if I press multiple times it will jump only once, as you can see here:
https://vid.me/aRfk
Thank you for helping.
I have created same scene in Unity3D Editor and played a little with same setup you have. And yes I had similar problems adding force on Update and also (but less) on FixedUpdate. But adding force on LateUpdate seems to work okay.
Here is my code:
public Rigidbody2D rb2dBall;
void LateUpdate()
{
if(Input.GetKeyUp(KeyCode.Space))
{
rb2dBall.AddForce (Vector2.up * 10f, ForceMode2D.Impulse);
}
}
And also I turned on interpolation:
I cant say why the physics bahaves like this, could be some bug in Unity3D 5.X since on FixedUpdate it should work fine.
Firstly, when working with physics in Unity, it's highly recomended to use the FixedUpdate method, instead of the Update. You can check in this link http://docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html
The second thing is that maybe you are not applying so much force at the ball, the force needed to give a quite impulse will depends of the mass of your ball's rigidbody. So try to do something like that:
GetComponent<Rigidbody>().AddForce(Vector2.up * 100, ForceMode.Impulse);
Change the fixed value 100 to adjust your needs.

Drawing line of sight between two actors

I am fresh learner of LibGDX. I am trying to learn LibGDX by developing a demo game. In the game when an army and enemy are visible to each other I want to draw a line of sight between them to prove that they see each other. The line of sight should increase gradually, say something like when we transfer file in windows 7 the green portion increases gradually. I am working with scene2D and have implemented Screen interface of scene2D.
You may want to look into a physics library. Either use it explicitly in your app (like Box2d or libgdx's BulletPhysics). Both of these have a concept of raycasting and some form of ray cast callback. This allows you to pick a "starting point" for your "line of sight" and see what the raycast hits/collides with.
If you don't want to use the physics library in your app, you could at least look at the source code for both, and roll your own, slimmed down functionality to achieve your line of sight goals.
So you are looking for something visually for the player and for calculations? I have no clue what you mean by the windows 7 file transfer thing.
It all depends on how accurate you want to have things but you need some kind of ray casting like Peter R is saying. You have libraries for this but depending on what you want this can be easy to implement yourself.
You take the Vector of a unit or army and the Vector of the enemy. Then check for obstructions between those Vectors. You should have a floatfor the distance each step of the line, the higher this is the more efficient but also less accurate since it could step over a small object.
Some crude untested pseudo code for 2D:
RayCast(Vector v1, Vector v2)
{
Vector2 p = v1;
Vector2 direction = (v2 - v1).normalize;
float distance = 0.5f;
float totalDistance = 200;
while (Distance(p & v2) > distance && Distance(p & v1) < totalDistance)
{
p += direction * distance;
if (some obstruction is at p)
{
//no line of sight
}
}
}
I have developed the game using AndEngine and i have used AndEngine box2D physics and i update the position between two players continuously as follows:
I have two players one player and other enemy. I have drawn the line and the end position of the line is given by player and enemy positions. I have done by getting their coordinates
//line of sight
final Line e1line = new Line(player.getX(), player.getY(), enemy.getX(), enemy.getY())
And finally i have used update handler to continusely move the line as the player moves as follows:
IUpdateHandler updatehand = new IUpdateHandler(){
#Override
public void onUpdate(float pSecondsElapsed) {
// line of sight and notifier update
e1line.setPosition(player.getX(), player.getY(), enemy1.getX(), enemy1.getY());
}
#Override
public void reset() {}
};

Panning the view of a gameObject instead of the camera in Unity3d?

I'm having a hard time to pan a view of a gameObject in Unity3d. I'm new to scripting and I'm trying to develop an AR (Augmented Reality) application for Android.
I need to have a gameObject (e.g. a model of a floor), from the normal top down view, rendered to a "pseudo" iso view, inclined to 45 degrees. As the gameObject is inclined, I need to have a panning function on its view, utilizing four (4) buttons (for left, right, forward(or up), backward(or down)).
The problem is that, I cannot use any of the known panning script snippets around the forum, as the AR camera has to be static in the scene.
Need to mention that, I need the panning function to be active only at the isometric view, (which I already compute with another script), not on top down view. So there must be no problem with the inclination of the axes of the gameObject, right?
Following, are two mockup images of the states, the gameObject (model floor) is rendered and the script code (from Unity reference), that I'm currently using, which is not very much functional for my needs.
Here is the code snippet, for left movement of the gameObject. I use the same with a change in -, +speed values, for the other movements, but I get it only move up, down, not forth, backwards:
#pragma strict
// The target gameObject.
var target: Transform;
// Speed in units per sec.
var speedLeft: float = -10;
private static var isPanLeft = false;
function FixedUpdate()
{
if(isPanLeft == true)
{
// The step size is equal to speed times frame time.
var step = speedLeft * Time.deltaTime;
// Move model position a step closer to the target.
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}
}
static function doPanLeft()
{
isPanLeft = !isPanLeft;
}
It would be great, if someone be kind enough to take a look at this post, and make a suggestion on how this functionality can be coded the easiest way, as I'm a newbie?
Furthermore, if a sample code or a tutorial can be provided, it will be appreciated, as I can learn from this, a lot. Thank you all in advance for your time and answers.
If i understand correctly you have a camera with some fixed rotation and position and you have a object you want to move up/down/left/right from the cameras perspective
To rotated an object to a set of angles you simply do
transform.rotation = Quaternion.Euler(45, 45, 45);
Then to move it you use the cameras up/right/forward in worldspace like this to move it up and left
transform.position += camera.transform.up;
transform.position -= camera.transform.right;
If you only have one camera in your scene you can access its transform by Camera.main.transform
An example of how to move it when someone presses the left arrow
if(Input.GetKeyDown(KeyCode.LeftArrow))
{
transform.position -= camera.transform.right;
}

Unity2D Android Touch misbehaving

I am attempting to translate an object depending on the touch position of the user.
The problem with it is, when I test it out, the object disappears as soon as I drag my finger on my phone screen. I am not entirely sure what's going on with it?
If somebody can guide me that would be great :)
Thanks
This is the Code:
#pragma strict
function Update () {
for (var touch : Touch in Input.touches)
{
if (touch.phase == TouchPhase.Moved) {
transform.Translate(0, touch.position.y, 0);
}
}
}
The problem is that you're moving the object by touch.position.y. This isn't a point inworld, it's a point on the touch screen. What you'll want to do is probably Camera.main.ScreenToWorldPoint(touch.position).y which will give you the position inworld for wherever you've touched.
Of course, Translate takes a vector indicating distance, not final destination, so simply sticking the above in it still won't work as you're intending.
Instead maybe try this:
Vector3 EndPos = Camera.main.ScreenToWorldPoint(touch.position);
float speed = 1f;
transform.position = Vector3.Lerp(transform.position, EndPos, speed * Time.deltaTime);
which should move the object towards your finger while at the same time keeping its movements smooth looking.
You'll want to ask this question at Unity's dedicated Questions/Answers site: http://answers.unity3d.com/index.html
There are very few people that come to stackoverflow for Unity specific question, unless they relate to Android/iOS specific features.
As for the cause of your problem, touch.position.y is define in screen space (pixels) where as transform.Translate is expecting world units (meters). You can convert between the two using the Camera.ScreenToWorldPoint() method, then creating a vector out of the camera position and screen world point. With this vector you can then either intersect some geometry in the scene or simply use it as a point in front of the camera.
http://docs.unity3d.com/Documentation/ScriptReference/Camera.ScreenToWorldPoint.html

How to collide objects with high speed in Unity

I try to create game for Android and I have problem with high speed objects, they don't wanna to collide.
I have Sphere with Sphere Collider and Bouncy material, and RigidBody with this param (Gravity=false, Interpolate=Interpolate, Collision Detection = Continuous Dynamic)
Also I have 3 walls with Box Collider and Bouncy material.
This is my code for Sphere
function IncreaseBallVelocity() {
rigidbody.velocity *= 1.05;
}
function Awake () {
rigidbody.AddForce(4, 4, 0, ForceMode.Impulse);
InvokeRepeating("IncreaseBallVelocity", 2, 2);
}
In project Settings I set: "Min Penetration For Penalty Force"=0.001, "Solver Interation Count"=50
When I play on the start it work fine (it bounces) but when speed go to high, Sphere just passes the wall.
Can anyone help me?
Thanks.
Edited
var hit : RaycastHit;
var mainGameScript : MainGame;
var particles_splash : GameObject;
function Awake () {
rigidbody.AddForce(4, 4, 0, ForceMode.Impulse);
InvokeRepeating("IncreaseBallVelocity", 2, 2);
}
function Update() {
if (rigidbody.SweepTest(transform.forward, hit, 0.5))
Debug.Log(hit.distance + "mts distance to obstacle");
if(transform.position.y < -3) {
mainGameScript.GameOver();
//Application.LoadLevel("Menu");
}
}
function IncreaseBallVelocity() {
rigidbody.velocity *= 1.05;
}
function OnCollisionEnter(collision : Collision) {
Instantiate(particles_splash, transform.position, transform.rotation);
}
EDITED added more info
Fixed Timestep = 0.02 Maximum Allowed Tir = 0.333
There is no difference between running the game in editor player and on Android
No. It looks OK when I set 0.01
My Paddle is Box Collider without Rigidbody, walls are the same
There are all in same layer (when speed is normal it all works) value in PhysicsManager are the default (same like in image) exept "Solver Interation Co..." = 50
No. When I change speed it pass other wall
I am using standard cube but I expand/shrink it to fit my screen and other objects, when I expand wall more then it's OK it bouncing
No. It's simple project simple example from Video http://www.youtube.com/watch?v=edfd1HJmKPY
I don't use gravity
See:
Similar SO Question
A community script that uses ray tracing to help manage fast objects
UnityAnswers post leading to the script in (2)
You could also try changing the fixed time step for physics. The smaller this value, the more times Unity calculates the physics of a scene. But be warned, making this value too small, say <= 0.005, will likely result in an unstable game, especially on a portable device.
The script above is best for bullets or small objects. You can manually force rigid body collisions tests:
public class example : MonoBehaviour {
public RaycastHit hit;
void Update() {
if (rigidbody.SweepTest(transform.forward, out hit, 10))
Debug.Log(hit.distance + "mts distance to obstacle");
}
}
I think the main problem is the manipulation of Rigidbody's velocity. I would try the following to solve the problem.
Redesign your code to ensure that IncreaseBallVelocity and every other manipulation of Rigidbody is called within FixedUpdate. Check that there are no other manipulations to Transform.position.
Try to replace setting velocity directly by using AddForce or similar methods so the physics engine has a higher chance to calculate all dependencies.
If there are more items (main player character, ...) involved related to the physics calculation, ensure that their code runs in FixedUpdate too.
Another point I stumbled upon were meshes that are scaled very much. Having a GameObject with scale <= 0.01 or >= 100 has definitely a negative impact on physics calculation. According to the docs and this Unity forum entry from one of the gurus you should avoid Transform.scale values != 1
Still not happy? OK then the next test is starting with high velocities but no acceleration. At this phase we want to know, if the high velocity itself or the acceleration is to blame for the problem. It would be interesting to know the velocities' values at which the physics engine starts to fail - please post them so that we can compare them.
EDIT: Some more things to investigate
6.7 m/sec does not sound that much so that I guess there is a special reason or a combination of reasons why things go wrong.
Is your Maximum Allowed Timestep high enough? For testing I suggest 5 to 10x Fixed Timestep. Note that this might kill the frame rate but that can be dfixed later.
Is there any difference between running the game in editor player and on Android?
Did you notice any drops in frame rate because of the 0.01 FixedTimestep? This would indicate that the physics engine might be in trouble.
Could it be that there are static colliders (objects having a collider but no Rigidbody) that are moved around or manipulated otherwise? This would cause heavy recalculations within PhysX.
What about the layers: Are all walls on the same layer resp. are the involved layers are configured appropriately in collision detection matrix?
Does the no-bounce effect always happen at the same wall? If so, can you just copy the 1st wall and put it in place of the second one to see if there is something wrong with this specific wall.
If not to much effort, I would try to set up some standard cubes as walls just to be sure that transform.scale is not to blame for it (I made really bad experience with this).
Do you manipulate gravity or TimeManager.timeScale from within a script?
BTW: are you using gravity? (Should be no problem just

Categories

Resources