Here I found a code that shakes the camera: https://gist.github.com/ftvs/5822103
But how to use it if I want to shake the camera only when a bullet hits something?
In the link you posted there are:
// How long the object should shake for.
public float shake = 0f;
If the shake variable is set to for example 1 the camera will shake as long as it is greater than one. The code is decreasing the value so that the number you set is equivalent to seconds you want the shake to last.
Then how to shake when bullet hits something? You can add code to the bullet that starts the shaking. This can be done in the collision of the bullet. Use something like this:
public class BulletScript : MonoBehaviour {
void OnCollisionEnter2D(Collision2D coll) {
GameObject.Find("Main Camera").GetComponent<CameraShake>().shake = 0.25f;
}
}
For this to work you need the bullet and the counter part to have 2D colliders.
PS. Find is really slow operation, so you might want to optimize the code by setting pointer to CameraShake into static variable only once in a scene.
Related
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() {}
};
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;
}
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
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
Currently I am developing a game using andengine. In my game I have to bring trial effect which follows finger like fruit ninja. I have tried Rendering with BaseGameActivity and LayoutGameActivity with xml file.
But while combining opengl Rendering with andengine RendererSurfaceView it shows some delay as well as sprite in RendererSurfaceView doesn't listen to the onAreaTouched().
I am in confusion. could you please help in what manner I have to bring Trial Effect like Fruit Ninja in my game?
Well, I'm not sure if I totally understand, but I may be able to start you off...
In your BaseGameActivity's onCreateScene method, after you create your scene, set a touch listener. In your listener check if it's a move event, so you can get the x and y coordinates.
scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
#Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
if (pSceneTouchEvent.isActionMove()) {
Log.d(App.LOG_TAG, "x: " + pSceneTouchEvent.getX() + " y: " + pSceneTouchEvent.getY());
return true;
}
return false;
}
});
You'll need to keep track of the coordinates and probably do a smoothing algorithm on them, then draw some graphic over that path.
I created something similar a while ago [wasn't intended but somehow I made it] but I kind of lost the code so I'll just explain the process to you
To create a trial effect all what you have to do is use particle systems and attach it on touch , move it with the finger [change it's location when isActionMove()] and detach [or have it fade out first so you get nice effect] it on isActionUp()
I used this process to create a flame effect that follows your finger, the rest is up to you and how you mess around with the particle emitter to make the particles appear as a slash