I'm working on a 2D game in Unity3D (using Orthello 2D).
Since I switched from Cocos2d and CoronaSDK, I'm wondering if there's a way of implementing the following behaviour for a sprite (or any Unity3D object) as it worked in Corona:
object = ...
transition.to ( object, { time = 1000, rotation = object.rotation + 100, onComplete = function ()
// do something
end })
So a sprite rotates by 100 degrees over 1 second.
In my script attached to a sprite I can have a rotation in my Update () function, but it's a bit different approach...
You can do it easily in an Update function.
float timer = 0f;
void Update()
{
if(timer <= 1)
{
// Time.deltaTime*100 will make sure we are moving at a constant speed of 100 per second
transform.Rotate(0f,0f,Time.deltaTime*100);
// Increment the timer so we know when to stop
timer += Time.deltaTime;
}
}
If you need to do another 100 degrees rotation you will just have to reset the timer.
You can see different version of the Rotate function here and more information about the lifesaver Time.deltaTime value here
There are several differnt ways of doing that. For example using a coroutine:
IEnumerator TweenRotation(Transform trans, Quaternion destRot, float speed, float threshold )
{
float angleDist = Quaternion.Angle(trans.rotation, destRot);
while (angleDist > threshold)
{
trans.rotation = Quaternion.RotateTowards(trans.rotation, destRot, Time.deltaTime * speed);
yield return null;
float angleDist = Quaternion.Angle(trans.rotation, destRot);
}
}
Related
I have a GameObject with Animator and looped animation clip.
This animation changes X coordinate from 0 to 10 and back.
I need to add another animation to the first one that increases GameObject's scale and changes its color to red simultaneously.
After scale and color change GameObject keeps these parameters and continues to move according to the first animation clip.
The only way I managed to work it around is writing a custom script with couroutine:
IEnumerator Animate()
{
float scaleDelta = 0.2f;
float colorDelta = 0.02f;
for (int i = 0; i < 50; i++)
{
spriteRenderer.color = new Color(
spriteRenderer.color.r,
spriteRenderer.color.g - colorDelta,
spriteRenderer.color.b - colorDelta);
transform.localScale = new Vector3(
transform.localScale.x + scaleDelta,
transform.localScale.y + scaleDelta,
transform.localScale.z);
yield return new WaitForSeconds(0.02f);
}
}
This works for linear interpolation, but requires to write additional code and write even more code for non-linear transformations.
How can I achieve the same result with Mecanim?
Sample project link: https://drive.google.com/file/d/0B8QGeF3SuAgTU0JWNGd2RnpUU00/view?usp=sharing
I have the following animation:
See on video: Animation Light
Note: Below image of animation control
How can I get the same result using a script? My intention is that the script has no "if".
Don't like this:
public float minIntensity;
public float maxIntensity;
public float intensityAmount;
private Light light;
void Awake(){
light = GetComponent<Light>();
}
void Update(){
if (light.intensity > maxIntensity) {
light.intensity -= intensityAmount * Time.deltaTime;
}
else if (light.intensity < minIntensity) {
light.intensity += intensityAmount * Time.deltaTime;
}
}
I wonder if there is any possibility to do this using some native function ... like: (Math.Clamp, Math.Lerp, Quaternion.Slerp) without any condition as "if" in the code.
Thank you in advance.
Well like you mentioned, you can just use a clamp:
light.intensity = Mathf.Clamp(value, minIntensity, maxIntensity)
However, despite the lack of detail on what type of animation you want, I am assuming you want to "ping pong" between the min and the max. If that is the case, we can use our friendly neighborhood sine wave for that.
public float Frequency = 10f;
public float Magnitude = 2f;
void Update() {
light.Intensity = Magnitude + Mathf.Sin(Time.timeSinceLevelLoad * Frequency) * Magnitude;
}
The sine wave will go from -1 to 1, the magnitude value will make it go from (-magnitude to +magnitude) Since we don't want a negative light intensity, we add magnitude to the start, so the end result is (0 to 2 * magnitude) You can change this to work however you desire, but the point should be clear.
The Frequency variable will change how fast we animate back and forth.
Hi How do I make bullets to collide with the objects in Processing ?
Bullets are fired and being translated and rotated
but whenever i try to use function dist() it always gives me 0 as the position of the vector
How do i get the correct vector position if i want the bullet to collide with objects using distance and make the the other object disappear ?
Here's the code
void move(){
passed = passed + time;
if (passed > bulletLife) {
alive = false;
}
forward.x = sin(theta);
forward.y = -cos(theta);
float speed = 15.0f;
velocity = PVector.mult(forward, speed);
side.add(forward);
void display(){
pushMatrix();
translate(side.x, side.y);
rotate(theta);
stroke(255);
ellipse(side.x, side.y, 30, 30);
popMatrix();
Thanks
You're getting 0 from dist() because translate() moves the coordinate system! I think, more than your question, you need to reconsider your code overall. You translate to side.x, side.y (which will then be 0,0 until you call popMatrix()) but then you draw the ellipse at side.x, side.y which is offset from its actual position.
In other words: if the position is 100,200, you're actually drawing the object at 200,400!
If you skip the translate() part, you can use this to draw your object:
void display() {
stroke(255);
ellipse(side.x, side.y, 30,30);
}
And this to check collision:
if (dist(side.x, side.y, bullet.x, bullet.y) == 0) {
collision = true;
}
else {
collision = false;
}
You can also see my collision-detection functions for Processing, which have lots of examples that might help.
Im trying to rotate my player to face where I last clicked. I've acutally manged to do this, but now I want to see the player rotate at a set speed instead of the sprite just changing rotation instantly.
Ive tried several methods I've found online, but none of them work for me. Here's what I have
void Update()
{
if (Input.GetMouseButtonDown (0))
{
Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
diff.Normalize();
float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation= Quaternion.Euler(0f, 0f, rot_z - 90);
Instantiate(ProjectilePrefab, transform.position, transform.rotation);
}
}
The code above works fine, but it shows no movement. I have tried to do this but the position is wrong and the rotation is instant as well:
Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
var newRotation = Quaternion.LookRotation(diff);
newRotation.y = 0.0f;
newRotation.x = 0.0f;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * 30);
ANy ideas?
Two problems here. First, the Slerp function is only called once after the user pressed the mouse button. You have to move it outside the if part or use a coroutine. Second, Slerp expects a float from 0 to 1 to indicate the progress and not time or deltaTime. The official examples covering the lerp functions are just bad, because using the time value would work only during the first second the game is running.
You need something like this
if (Input.GetMouseButtonDown (0)) {
// your other stuff here
float starTime = Time.time;
}
float t = Time.time - startTime;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, t);
The rotation would finish after one second. If you want it faster or slower just multiply t with a factor.
I found the answer. This is how I made it work
if (Input.GetMouseButtonDown (0)) {
target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
rotateToTarget = true;
print ("NEW TARGET: " + target);
}
if (rotateToTarget == true && target != null) {
print ("Rotating towards target");
targetRotation = Quaternion.LookRotation (transform.position - target.normalized, Vector3.forward);
targetRotation.x = 0.0f;//Set to zero because we only care about z axis
targetRotation.y = 0.0f;
player.transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, Time.deltaTime * rotationSpeed);
if (Mathf.Abs (player.transform.rotation.eulerAngles.z - targetRotation.eulerAngles.z) < 1) {
rotateToTarget = false;
travelToTarget = true;
player.transform.rotation = targetRotation;
print ("ROTATION IS DONE!");
}
}
So I’m trying to give an obj some physics, and have work with the example of the bouncing ball that processing comes with, and I have make it instead of a ball to be a cylinder, but I can’t find the way to make the obj to have the physics.
I’m importing the obj with the library saito.objloader. I have this code, which is the invocation of the obj
import processing.opengl.*;
import saito.objloader.*;
OBJModel modelCan;
PVector location; // Location of shape
PVector velocity; // Velocity of shape
PVector gravity; // Gravity acts at the shape's acceleration
float rotX, rotY;
void setup() {
size(1028, 768, OPENGL);
frameRate(30);
modelCan = new OBJModel(this, "can.obj", "absolute", TRIANGLES);
modelCan.scale(50);
modelCan.translateToCenter();
modelCan.enableTexture();
location = new PVector(100,100,100);
velocity = new PVector(1.5,2.1,3);
gravity = new PVector(0,0.2,0);
}
void draw() {
background(129);
lights();
// Add velocity to the location.
location.add(velocity);
// Add gravity to velocity
velocity.add(gravity);
// Bounce off edges
if ((location.x > width) || (location.x < 0)) {
velocity.x = velocity.x * -1;
}
if (location.y > height) {
// We're reducing velocity ever so slightly
// when it hits the bottom of the window
velocity.y = velocity.y * -0.95;
location.y = height;
}
if (location.z < -height || location.z > 0) { //note that Zaxis goes 'into' the screen
velocity.z = velocity.z * -0.95;
//location.z = height;
}
println("location x: "+location.x);
println("location y: "+location.y);
println("location z: "+location.z);
println("velocidad x: "+velocity.x);
println("velocidad y: "+velocity.y);
println("velocidad z: "+velocity.z);
pushMatrix();
translate(width/2, height/2, 0);
modelCan.draw();
popMatrix();
}
I hope you guys can help me! Thanks!
The bouncing ball example is a very simple example, and I guess you can't apply it to a cylinder in an easy way.
You might want to have a look at these sites :
http://www.wildbunny.co.uk/blog/2011/04/20/collision-detection-for-dummies/
http://shiffman.net/ (his book is essential )
https://github.com/shiffman/Box2D-for-Processing (again : Daniel Shiffman)
Collision detection is made in computer time : it means that it's correlated with the frequency of your program execution. For instance, the velocity of an object can be so big that between two render cycles your first object is passing through your second object: collision detection won't happen. They didn't collide during the previous cycle, and don't collide during the current cycle.
That's why some physics "engine" like Box2D try to anticipate the collision, computing the bounding box of each object.
If you want to make accurate collision detection in 3D, you can look at the Bullet library, used in many games and movies : http://bulletphysics.org/wordpress/ but the learning curve might be large.
In your program, you can try to give a threshold to your collision detection (and add the dimensions of your object to its position, if you want the whole body to collide, not only its center !): if your object's position is between your limit and (your limit +/- a threshold) consider it's colliding, but you won't totally avoid tunnelling.