MoveModifier while rotating in Andengine - andengine

Im trying to make the drawback of a gun, for this the gun should rotate a little bit and go back too, then it should go front a little bit (simulating the repositioning if the shooter).
Doing this with MoveByModier requires changing it in every manageUpdate and some trigonometry. If i dont do it this way i could do it with 2 routes (one Modifier for the pull and another the repositioning ) but its still hard
So, Is there a MoveModifier that its independent from position AND rotation?

After some time i figured out how to make the 2 points animation.
public void drawback (Sprite sprite, float DeltaAngle, float drawback){
Vector2 center= new Vector2(sprite.getRotationCenterX(),sprite.getRotationCenterY());
Vector2 radiusPoint = new Vector2(sprite.getWidth(),sprite.getHeight());
float radius = radiusPoint.dst(center)/PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
Vector2 currentPosition= new Vector2(sprite.getX(),sprite.getY());
Vector2 pointA = new Vector2(
(float)Math.cos(Math.toRadians(DeltaAngle/2+180))*drawback + Float.valueOf (sprite.getX()),
(float)Math.sin(Math.toRadians(DeltaAngle/2+180))*drawback + Float.valueOf (sprite.getY()) );
Vector2 pointB = new Vector2(
(float) Math.cos (Math.toRadians((DeltaAngle)))*radius + Float.valueOf (sprite.getX()),
(float) Math.sin (Math.toRadians((DeltaAngle)))*radius + Float.valueOf (sprite.getY()) );
sprite.registerEntityModifier(new ParallelEntityModifier(
new RotationByModifier(2,15),
new SequenceEntityModifier(
new PathModifier(.5f,new PathModifier.Path(
new float[]{currentPosition.x,pointA.x},
new float[]{currentPosition.y,pointA.y}))),
new PathModifier(1.5f,new PathModifier.Path(
new float[]{pointA.x,pointB.x},
new float[]{pointA.y,pointB.y}))
));}
I belive the trygonometry can be simplified, but i will leave it to a curious commenter

Related

Unity Physics: How To Limit Rotation of Object Moved by Gravity

I have a Child object, an Iron Bar (with Rigidbody and Gravity), connected to a Long Arm (w/ Rigidbody and isKinematic). I need to restrict the rotation of the Iron Bar from 1 to 40 degree angles only so it won't go overboard and hit the Long Arm. Please refer to attached image for more info. I tried several approaches from using a Hinge Joint and its Limit options and also through code. But I cannot seem to solve this problem. Right now I have this script attached to the Iron Bar but it does not seem to have any effect.
public Transform targetTransform;
private Vector3 _currentAngle;
private Vector3 _targetAngle;
float rotationX;
void FixedUpdate () {
transform.right = targetTransform.transform.right; //-- To make the Iron Bar follow player rotation
rotationX = transform.eulerAngles.x;
if (rotationX > 40) {
_targetAngle = new Vector3 (40, transform.eulerAngles.y, transform.eulerAngles.z);
_currentAngle = new Vector3 (Mathf.LerpAngle (transform.eulerAngles.x, _targetAngle.x, Time.deltaTime), Mathf.LerpAngle (transform.eulerAngles.y, _targetAngle.y, Time.deltaTime), Mathf.LerpAngle (transform.eulerAngles.z, _targetAngle.z, Time.deltaTime));
transform.eulerAngles = _currentAngle;
} else if (rotationX < 1) {
_targetAngle = new Vector3 (1, transform.eulerAngles.y, transform.eulerAngles.z);
_currentAngle = new Vector3 (Mathf.LerpAngle (transform.eulerAngles.x, _targetAngle.x, Time.deltaTime), Mathf.LerpAngle (transform.eulerAngles.y, _targetAngle.y, Time.deltaTime), Mathf.LerpAngle (transform.eulerAngles.z, _targetAngle.z, Time.deltaTime));
transform.eulerAngles = _currentAngle;
}
}
Would appreciate any help you can provide. Thanks for taking a look.
Note: This is a revised question but related to the initial one which I have already partially solved. Revision was made for further clarification.

How to make a player only move in 1 direction (Unity)

I am trying to create a game in Unity where the player can only move in the direction it is facing, but the following code allows the player to move in all 4 directions.
(This is for a 3D project)
Any help would be appreciated! Thanks!
public class PlayerController : MonoBehaviour {
public float speed;
private Rigidbody rb;
void Start() {
rb = GetComponent<Rigidbody>();
}
void FixedUpdate() {
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
}
}
So I didn't get what you wanted: first you said you wanted it to move only forward, then the only thing you have to do is get when he pressed a key and move forward while is not unpressed.
If you wanted to say that it can move all directions BUT only one at a time, the you will have to put the same code but with some changes:
First of all to make it move forward you have to get the forward of the transform, otherwise it will move in the same direction if you rotate it (you don't want that, no?).
Vector3 moveDirection = (transform.forward * Input.GetAxis("Vertical") + transform.right * Input.GetAxis("Horizontal")).normalized;
moveDirection.y = 0;
rb.velocity = moveDirection;
Then, to make that it ONLY moves to one direction at a time, you have to put the priority of the greatest axis number and if it's equal then you should think if you want to move forward or right (with it's axis value).
From the code you posted, I'm not sure where you are storing the player's facing-direction. However, I presume that it is stored as a Quaternion. If you have a player rotation quaternion called playerRotation, then you could do this (warning - untested):
Vector3 input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
Vector3 normal = playerRotation * Vector3.forward;
Vector3 movement = Vector3.Dot(normal, input) * input;
If the game is first-person, then you can take a shortcut and just use Camera.current.transform.forward instead of the normal vector.
This will project the input direction onto the normal with the player's facing direction so that your movement force can only be in that direction.

how to get background to scroll with player height in unity?

I am making an endless jumper. I am trying to get the BG to scroll down based on the players height.
I have seen code that moves the code at a specific speed:
public float speed = .5f;
void Updated(){
Vector2 offset = new Vector2(0, Time.deltatime * speed);
GetComponent<Renderer>().material.mainTextureOffset = offset;
}
I want to move it with the height of the player.
public float PlayerHeight;
So now I need to set the height of the BG. I can't figure out how to do this part.
Transform background;
public float backgroundHeightY;
public GameObject BackGround;
from here I am stuck. I don't want it to move with the camera, but move at a certain rate based on the height of the player. Any help would be awesome.
It sounds like you have a background that has a fixed position relative to the camera, but you want the background to scroll "against" the player as they move up and down, giving a parallax effect?
public Transform player;
public float multiplier = 0.1f; //Tweak this
void Update(){
Vector2 offset = new Vector2(0, player.position.y * multiplier);
GetComponent<Renderer>().material.mainTextureOffset = offset;
}
I have it working well going up, but not down. Here is how it is working going up. I have adjusted the backgroundModifier to fit the timing I need.
//Changes the BG position
changeAmount = (playerHeightY - currentCameraHeight)/backgroundModifier;
Vector3 temp = new Vector3(0, changeAmount, 0);
BackGround.transform.position += temp;
Anyone have an idea on how to get the falling to work. I feel like I am making this harder than it needs to be.
Here is how I finally did this. I actually switched the camera from orthographic to perspective. It took a lot of tweaking to layout, but it ended up working perfectly well. So the code I have above I deleted.

How to jump and fall in Unity?

I am coding a game jump in Unity. How can I jump (move) like in the Jupiter jump game, so that at a touch my hero will fall at high speed?
###
public float forceFly;
void Update () {
rigidbody2D.velocity = Vector2.zero;
rigidbody2D.AddForce (new Vector2 (0, 1) forceFly);
if(Input.GetMouseButtonDown(0)){
// ?
}
This question is horribly structured, and it really looks like you didn't even try. What you'll need to do is get the current position of the object by its transform.
gameObject.transform.position
and apply vector math on it. In this case you're wanting to move the Y axis up (to move into the air). A very simple implementation of this would be like so:
gameObject.transform.position = new Vector3(transform.position.x, transform.position.y + forceFly, transform.position.z);
where forcefly is the amount that you'll "jump" every second.

Unity - Limit Camera Movement XY axis

I have the following code which works really well for scrolling map using the draggable mouse. I am trying to define limits so that I cannot scroll too far in either the x or y co-ordinates. I've seen various examples of code, such as:
"transform.position.x = Mathf.Clamp(-100, 100);" though have not been able to incorporate it into the code. I am a bit of a beginner to all this and have just done a 2D tutorial animating zombies and have a camera that can scroll, but would like to add limits to how far it can scroll in any given directions.
Thanks heaps
Adam
using UnityEngine;
using System.Collections;
public class ViewDrag : MonoBehaviour {
Vector3 hit_position = Vector3.zero;
Vector3 current_position = Vector3.zero;
Vector3 camera_position = Vector3.zero;
float z = 0.0f;
// Use this for initialization
void Start () {
}
void Update(){
if(Input.GetMouseButtonDown(0)){
hit_position = Input.mousePosition;
camera_position = transform.position;
}
if(Input.GetMouseButton(0)){
current_position = Input.mousePosition;
LeftMouseDrag();
}
}
void LeftMouseDrag(){
// From the Unity3D docs: "The z position is in world units from the camera." In my case I'm using the y-axis as height
// with my camera facing back down the y-axis. You can ignore this when the camera is orthograhic.
current_position.z = hit_position.z = camera_position.y;
// Get direction of movement. (Note: Don't normalize, the magnitude of change is going to be Vector3.Distance(current_position-hit_position)
// anyways.
Vector3 direction = Camera.main.ScreenToWorldPoint(current_position) - Camera.main.ScreenToWorldPoint(hit_position);
// Invert direction to that terrain appears to move with the mouse.
direction = direction * -1;
Vector3 position = camera_position + direction;
transform.position = position;
}
}
What exactly is the error you are getting? I imagine it is something along the lines of being unable to modify the return value of position because it is not a variable.
If this is the case, you should however be able to set the whole position vector at once. So try something along the lines of this:
var pos = transform.position;
transform.position = new Vector3(
Math.clampf(pos.x, -100, 100),
Math.clampf(pos.y, -100, 100),
pos.z
);
You may need to swap around clamping Y and Z, depending on how you are using them.