I am trying to use iTween’s Turret Example. I did everything good so far except following mouse position with rotating turret.
[30891-ekran+resmi+2014-08-10+21.02.19.png|30891]
I have a turret as you can see in the image above and I want it to follow the target(Mouse Position) by rotating around it self.
For that, iTween has great example but it is only for 3d So, I tried to implement it in 2D but whatever I did I couldn’t succeed.
using UnityEngine;
using System.Collections;
public class CannonController : MonoBehaviour
{
public Rigidbody2D bullet;
public Camera mainCam;
public GameObject pivot;
float pivotX;
float pivotY;
public Transform target;
float smoothTime = 0.3f;
float xOffset = 1f;
float yOffset = 1f;
Vector2 velocity;
Transform thisTransform;
void Start ()
{
thisTransform = transform;
}
// Update is called once per frame
void Update ()
{
pivotX = pivot.transform.position.x;
pivotY = pivot.transform.position.y;
//rotation:
Vector2 mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
mousePos.y = 0;
gameObject.transform.rotation = Quaternion.Euler (new Vector3 (mousePos.x, 0, mousePos.y));
Vector2 worldPos = Camera.main.ScreenToWorldPoint (mousePos);
iTween.LookUpdate (gameObject, iTween.Hash ("looktarget", worldPos, "time", 2, "axis", "y"));
//rotation:
// Vector3 mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
// mousePos.z = 0;
// gameObject.transform.position = mousePos;
// Vector3 worldPos = Camera.main.ScreenToWorldPoint (mousePos);
// iTween.LookUpdate (gameObject, iTween.Hash ("looktarget", worldPos, "time", 2, "axis", "y"));
//fire:
if (Input.GetMouseButtonDown (0)) {
Rigidbody2D clone = (Rigidbody2D)Instantiate (bullet, new Vector2 (pivotX, pivotY), transform.rotation);
clone.velocity = transform.TransformDirection (Vector2.up * 10f);
}
}
}
Commented parts under “rotation:” was the iTween’s original code for rotating by following mouse position for 3D environment.
The other parts under “rotation:” with Vector2 code is my code.
This was the closest trial I could ever made, but I it is not really working. It only moves the turret on x-axis just a little bit (not much!)
But I guess, the turret should be rotate around z-axis.
So, can anyone help me to rotate the turret around z-axis smoothly by following mouse position ?