脚本一共有两个,一个是发射脚本,还有个子弹脚本
发射的脚本,作用很明显,就是创建实例子弹
子弹的脚本,也很简单,就是创建出来后,子弹会从A到B移动
发射脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Fashe : MonoBehaviour
{
public GameObject BulletPrefab;
public Transform LocateA;
//public Transform locateB;
public float intaval=0.5f;//子弹发射时间间隔
private float count = 0f;//计时器
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
count = count + Time.deltaTime;
if(count>=intaval)
{
Instantiate(BulletPrefab, LocateA.transform.position, Quaternion.identity);//创建实例
count = 0;
print("fashe");
}
}
}
子弹脚本
using UnityEngine;
using System.Collections;
public class BulletAB : MonoBehaviour
{
// Transforms to act as start and end markers for the journey.
private GameObject startMarker;
private GameObject endMarker;
public GameObject Obj;
public float life = 2;
// Movement speed in units/sec.
public float speed = 1.0f;
// Time when the movement started.
private float startTime;
// Total distance between the markers.
private float journeyLength;
void Start()
{
startMarker=GameObject.Find("AMarker");
endMarker = GameObject.Find("BMarker");
// Keep a note of the time the movement started.
startTime = Time.time;//记录初始时间
// Calculate the journey length.
journeyLength = Vector3.Distance(startMarker.transform.position, endMarker.transform.position);
var startPos = startMarker.transform.position;//记录起始位置坐标;
Destroy(gameObject, life);
}
// Follows the target position like with a spring
void Update()
{
// Distance moved = time * speed.
float distCovered = (Time.time - startTime) * speed;//当前时间减去初始时间乘以速度,其实就是位移
// Fraction of journey completed = current distance divided by total distance.
float fracJourney = distCovered / journeyLength;
// Set our position as a fraction of the distance between the markers.
Obj.transform.position = Vector3.Lerp(startMarker.transform.position, endMarker.transform.position, fracJourney);
}
}
用法:要在场景中设立A点跟B点,A点名字为“startMarker” B点名字为“endMarker”,这两个点是子弹必须的,是要寻找的点。
如果想让B点运动起来,那么需要在B点写一个往复的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveBMarker : MonoBehaviour
{
public float Frequency=1;
public float speed = 10;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float movePara = Mathf.Sin(Frequency*Time.time);
this.transform.Translate(new Vector3(0, 0, speed * movePara*Time.deltaTime));
}
}